Skip to content

Instantly share code, notes, and snippets.

@mshabunin
Created May 14, 2020 13:13
Show Gist options
  • Save mshabunin/ea9006dff9ea7828866d8bd1ff7c01ed to your computer and use it in GitHub Desktop.
Save mshabunin/ea9006dff9ea7828866d8bd1ff7c01ed to your computer and use it in GitHub Desktop.
Pixels and contours
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace std;
int main()
{
const uchar B = 0x00;
const uchar F = 0xFF;
uchar data[] = {
B, B, B, B, B, B,
B, B, F, F, F, B,
B, F, F, F, F, B,
B, F, F, F, B, B,
B, F, F, F, B, B,
B, B, B, B, B, B,
};
Mat img(Size(6, 6), CV_8UC1, data);
vector<Mat> cont;
findContours(img, cont, RETR_LIST, CHAIN_APPROX_NONE);
for (Mat& c : cont)
cout << c.t() << endl << "Area: " << contourArea(c) << endl;
cvtColor(img, img, COLOR_GRAY2BGR);
drawContours(img, cont, 0, Scalar(200, 200, 200), 1);
double scale = 64;
Mat viz;
resize(img, viz, Size(), scale, scale, INTER_AREA);
for (Mat& c : cont)
c *= scale;
drawContours(viz, cont, 0, Scalar(0, 255, 0), 3);
for (Mat& c : cont)
for (int i = 0; i < c.rows; ++i)
{
const Point p = c.at<Point>(i, 0);
drawMarker(viz, p, Scalar(200, 0, 200), MARKER_DIAMOND, 10, 3);
stringstream out;
out << "(" << p.x / scale << ", " << p.y / scale << ")";
putText(viz, out.str(), p + Point(5, 15), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 240), 1, LINE_AA);
}
imshow("Image", viz);
waitKey(0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment