Detect multiple fruits in an image using OpenCV

OpenCV detect multiple fruits in image


I recently encountered an image algorithm question in an interview, which required:
(1) Detect multiple apples in an image and identify them.
(2) When marking, the apples in the image need to be given serial numbers from largest to smallest and displayed.
Based on the above two points, while preparing to use C++ to write code, use OpenCV to perform related operations, record them here.

Attached are some renderings:
Insert image description here

1 Idea
As for the image itself, because apples are red, based on this characteristic, the idea is to first classify them according to color, and then extract the red area in the image , and then detect and label the image.

step1: filtering

	Mat img = imread("D:/VSprojection/detect_apple/detect_apple/1.jpeg", cv::IMREAD_COLOR);//用来输出
	//step1:BGR->HSV
	Mat src_HSV;
	cvtColor(src, src_HSV, COLOR_BGR2HSV);
	//imshow("source_image", src);
	medianBlur(src_HSV, src_HSV, 5);

step2: Extract the red area

//step2:提取苹果
	int imgrow = src.rows;
	int imgcol = src.cols;
	for (int m = 0; m < imgrow; m++)
	{
   
    
    
		for (int n = 0; n < imgcol; n++)
		{
   
    
    
			//提取红色区域
			if (!((((src_HSV.at<Vec3b>(m, n)[0] >= 0) && (src_HSV.at<Vec3b>(m, n)[0] <= 15)) ||
				(src_HSV.at<Vec3b>(m, n)[0] >= 125) && (src_HSV.at<Vec3b>(m, n)[0] <= 180)) && 	(src_HSV

Guess you like

Origin blog.csdn.net/qq_42221707/article/details/128025782