3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
fanfuhan OpenCV 教學057 ~ opencv-057-二值化圖像分析(點多邊形測試) 資料來源: https://fanfuhan.github.io/ https://fanfuhan.github.io/2019/04/18/opencv-057/ GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV 對於輪廓圖像,有時候還需要判斷一個點是在輪廓內部還是外部,OpenCV中實現這個功能的API叫做點多邊形測試,它可以準確的得到一個點距離多邊形的距離,如果點是輪廓點或者屬於輪廓多邊形上的點,距離是零,如果是多邊形內部的點是是正數,如果是負數返回表示點是外部。 C++ #include #include using namespace std; using namespace cv; /* * 二值图像分析(点多边形测试) */ int main() { Mat src = imread("../images/my_mask.png"); if (src.empty()) { cout << "could not load image.." << endl; } imshow("input", src); // 二值化 Mat dst, gray, binary; cvtColor(src, gray, COLOR_BGR2GRAY); threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU); // 轮廓发现与绘制 vector> contours; vector hierarchy; findContours(binary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point()); Mat image = Mat::zeros(src.size(), CV_32FC3); // 对轮廓内外的点进行分类 for (int row = 0; row < src.rows; ++row) { for (int col = 0; col < src.cols; ++col) { double dist = pointPolygonTest(contours[0], Point(col, row), true); if (dist == 0) { image.at(row, col) = Vec3f(255, 255, 255); } else if (dist > 0) { image.at(row, col) = Vec3f(255 - dist, 0, 0); } else { image.at(row, col) = Vec3f(0, 0, 255 + dist); } } } convertScaleAbs(image, image); imshow("points", image); waitKey(0); return 0; } Python import cv2 as cv import numpy as np src = cv.imread("D:/images/my_mask.png") cv.namedWindow("input", cv.WINDOW_AUTOSIZE) cv.imshow("input", src) gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) cv.imshow("binary", binary) # 轮廓发现 image = np.zeros(src.shape, dtype=np.float32) out, contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) h, w = src.shape[:2] for row in range(h): for col in range(w): dist = cv.pointPolygonTest(contours[0], (col, row), True) if dist == 0: image[row, col] = (255, 255, 255) if dist > 0: image[row, col] = (255-dist, 0, 0) if dist < 0: image[row, col] = (0, 0, 255+dist) dst = cv.convertScaleAbs(image) dst = np.uint8(dst) # 显示 cv.imshow("contours_analysis", dst) cv.imwrite("D:/contours_analysis.png", dst) cv.waitKey(0) cv.destroyAllWindows()

本文由jashliaoeuwordpress提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦