在线PS随便画了一个四边形如图:
代码:
#include "stdafx.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/video/background_segm.hpp> #include "iostream" using namespace cv; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { Mat src = imread("E://test.jpg", 1); Mat src_G; Mat src_B; cvtColor(src, src_G, CV_BGR2GRAY); threshold(src_G, src_B, 100, 255, CV_THRESH_BINARY); Mat src_V = Mat(src_B.rows, src_B.cols, CV_8UC1); Mat src_H = Mat(src_B.rows, src_B.cols, CV_8UC1); Mat src_O = Mat(src_B.rows, src_B.cols, CV_8UC1); for (int i = 0; i < src_B.cols; i++) for (int j = 0; j < src_B.rows; j++) { src_V.at<uchar>(j, i) = 255; src_H.at<uchar>(j, i) = 255; } for (int i = 0; i < src_V.cols; i++)//垂直扫描; for (int j = 1; j < src_V.rows-1; j++) { if (src_B.at<uchar>(j, i) == 0 && src_B.at<uchar>(j - 1, i) == 255 )//该像素为最外层黑色素; { src_V.at<uchar>(j, i) = 0; while (src_B.at<uchar>(j, i) == 0 && j < src_V.rows-1) { if (src_B.at<uchar>(j + 1, i) == 255 && i < src_V.cols&&j+1 < src_V.rows) { src_V.at<uchar>(j, i) = 0; break; } j++; } } } for (int i = 0; i < src_H.rows; i++) for (int j = 1; j < src_H.cols - 1; j++) { if (src_B.at<uchar>(i,j) == 0 && src_B.at<uchar>(i,j-1) == 255)//该像素为最外层黑色素; { src_H.at<uchar>(i, j) = 0; while (src_B.at<uchar>(i,j) == 0 && j < src_H.cols - 1) { if (src_B.at<uchar>(i, j+1) == 255 && i < src_H.rows&&j + 1 < src_H.cols) { src_H.at<uchar>(i,j) = 0; break; } j++; } } } for (int i = 0; i < src_B.rows; i++) for (int j = 1; j < src_B.cols - 1; j++) { if (src_V.at<uchar>(i, j) == 0 || src_H.at<uchar>(i, j) == 0) src_O.at<uchar>(i, j) = 0; } imshow("3", src_O); imshow("2", src_V); imshow("1", src_H); waitKey(0); return 0; }
输出图:那么在写这个算法的时候,由于像素点容易越界,所以各种内存报错,那么这种错误调试完依旧出现,即使程序已经没有错误(无引用源等)需要重新生成解决方案后方可成功调试。
时间: 2024-10-13 11:19:05