#include #include #include #include #include #include #include #include #include #include #include #include #include #include "opencv2/core/opengl.hpp" // #include "t0.cpp" // #include "t1.cpp" using namespace std; using namespace cv; #define STB_IMAGE_IMPLEMENTATION #include "stb_image/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image/stb_image_write.h" cv::Mat out; cv::Mat img = cv::imread("fish.png"); void contours_algo() { std::vector> contours; // cv::namedWindow("In",0); // cv::namedWindow("Out",0); std::vector hierarchy; cv::findContours(out,contours,hierarchy,cv::RETR_LIST,cv::CHAIN_APPROX_SIMPLE); cv::Mat mask = cv::Mat::zeros(img.size(),CV_8UC3); cv::drawContours(mask,contours,-1,cv::Scalar(255,255,255),5); contours.push_back(vector()); hierarchy.push_back(cv::Vec4i()); cv::imshow("In",img); cv::imshow("Mask", mask); cv::imshow("Out",out); cv::waitKey(0); } float perpendicularDistance(const Point& p, const Point& lineStart, const Point& lineEnd) { float x = p.x; float y = p.y; float x1 = lineStart.x; float y1 = lineStart.y; float x2 = lineEnd.x; float y2 = lineEnd.y; float A = x - x1; float B = y - y1; float C = x2 - x1; float D = y2 - y1; float dot = A *C + B *D; float len_sq = C * C + D * D; float param = dot / len_sq; float xx, yy; if (param < 0) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * C; yy = y1 + param * D; } float dx = x - xx; float dy = y - yy; return sqrt(dx * dx + dy * dy); } void simplifyContourRDP(const vector& contour, int startIdx, int endIdx, float epsilon, vector& simplifiedContour) { if (endIdx <= startIdx + 1) { // Base case: only two points in the line segment return; } float maxDistance = 0.0; int maxDistanceIdx = 0; Point lineStart = contour[startIdx]; Point lineEnd = contour[endIdx]; // Find the point with the maximum perpendicular distance // from the line segment for (int i = startIdx + 1; i < endIdx; ++i) { float distance = perpendicularDistance(contour[i], lineStart, lineEnd); if (distance > maxDistance) { maxDistance = distance; maxDistanceIdx = i; } } // If the maximum distance is greater than epsilon, // include the point in the simplified contour if (maxDistance > epsilon) { simplifiedContour.push_back(contour[maxDistanceIdx]); // Simplify the left and right sub-contours simplifyContourRDP(contour, startIdx, maxDistanceIdx, epsilon, simplifiedContour); simplifyContourRDP(contour, maxDistanceIdx, endIdx, epsilon, simplifiedContour); } } vector simplifyContourRDP(const vector& contour, float epsilon) { vector simplifiedContour; simplifiedContour.push_back(contour.front()); simplifiedContour.push_back(contour.back()); simplifyContourRDP(contour, 0, contour.size() - 1, epsilon, simplifiedContour); return simplifiedContour; } int main(int argc , char **argv) { cv::Mat bilateralimg,medianimg,out; cv::Mat edges = cv::imread("fish.png", cv::IMREAD_GRAYSCALE); cv::Mat img = cv::imread("fish.png"); cv::Mat img2 = cv::imread("fish.png",cv::IMREA.