Skip to content

Instantly share code, notes, and snippets.

@insaneyilin
Created January 1, 2021 02:34
Show Gist options
  • Save insaneyilin/164267440dd19511f20f8546c3c98296 to your computer and use it in GitHub Desktop.
Save insaneyilin/164267440dd19511f20f8546c3c98296 to your computer and use it in GitHub Desktop.
Draw Dashed/Dotted line in OpenCV
// reference: https://ddorobot.tistory.com/entry/OpenCV-Draw-DotDash-Line
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include "opencv2/opencv.hpp"
void DrawDashedLine(cv::Mat& img, cv::Point pt1, cv::Point pt2,
cv::Scalar color, int thickness, std::string style,
int gap) {
float dx = pt1.x - pt2.x;
float dy = pt1.y - pt2.y;
float dist = std::hypot(dx, dy);
std::vector<cv::Point> pts;
for (int i = 0; i < dist; i += gap) {
float r = static_cast<float>(i / dist);
int x = static_cast<int>((pt1.x * (1.0 - r) + pt2.x * r) + .5);
int y = static_cast<int>((pt1.y * (1.0 - r) + pt2.y * r) + .5);
pts.emplace_back(x, y);
}
int pts_size = pts.size();
if (style == "dotted") {
for (int i = 0; i < pts_size; ++i) {
cv::circle(img, pts[i], thickness, color, -1);
}
} else {
cv::Point s = pts[0];
cv::Point e = pts[0];
for (int i = 0; i < pts_size; ++i) {
s = e;
e = pts[i];
if (i % 2 == 1) {
cv::line(img, s, e, color, thickness);
}
}
}
}
int main(int argc, char **argv) {
cv::Mat img(200, 200, CV_8UC3, cv::Scalar(0, 0, 0));
// dotted
DrawDashedLine(img, cv::Point(10, 10), cv::Point(100,100), cv::Scalar(0, 0, 255), 2, "dotted", 10);
// dashed
DrawDashedLine(img, cv::Point(199, 10), cv::Point(100,100), cv::Scalar(0, 255, 0), 2, "", 10);
cv::imshow("dotted dashed", img);
cv::waitKey(0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment