opencv各种小程序代码

时间:2023-02-22 08:13:07

各种小程序代码

void COpenCV::OnOpencvCvcanny()
{
	// TODO:  在此添加命令处理程序代码
		
		IplImage* imgColor = cvLoadImage("C:\\Users\\Administrator\\Desktop\\159.jpg", 0);
		IplImage* contoursImage = cvCreateImage(cvSize(imgColor->width, imgColor->height), 8, 1);
		IplImage* img = cvCreateImage(cvSize(imgColor->width, imgColor->height), 8, 1);

		IplImage* imgmid = cvCloneImage(imgColor);


		CvSeq* contours = 0;

		//提取图像img的轮廓信息
		cvCanny(imgmid, img, 80, 180, 3);

		//cvSaveImage("midimg/Canny.jpg", img);

		cvNamedWindow("image", 1);
		cvShowImage("image", imgColor);

		cvNamedWindow("contours", 1);
		cvShowImage("contours", img);

		cvWaitKey(0);
		cvSaveImage("C:\\Users\\Administrator\\Desktop\\cvCanny.jpg", img);

		//cvReleaseMemStorage(&storage);
		cvReleaseImage(&img);
		cvReleaseImage(&contoursImage);
		cvReleaseImage(&imgColor);

}


void COpenCV::OnOpencvHist()
{
	// TODO:  在此添加命令处理程序代码
	IplImage* src=cvLoadImage("D:\\18.jpg", 1);

	//Compute the HSV image and decompose it into separate planes.
	IplImage* hsv = cvCreateImage(cvGetSize(src), 8, 3);
	//rgb色彩空间转换到hsv色彩空间
	cvCvtColor(src, hsv, CV_BGR2HSV);

	cvNamedWindow("hsv", 1);
	cvShowImage("hsv", hsv);

	IplImage* h_plane = cvCreateImage(cvGetSize(src), 8, 1);
	IplImage* s_plane = cvCreateImage(cvGetSize(src), 8, 1);
	IplImage* v_plane = cvCreateImage(cvGetSize(src), 8, 1);
	IplImage*  planes[] = { h_plane, s_plane };

	//分割为单通道图像
	cvCvtPixToPlane(hsv, h_plane, s_plane, v_plane, 0);

	cvNamedWindow("h_plane", 1); 
	cvShowImage("h_plane", h_plane); 
	cvNamedWindow("s_plane", 1);  
	cvShowImage("s_plane", s_plane); 
	cvNamedWindow("v_plane", 1); 
	cvShowImage("v_plane", v_plane);

	//Build the histogram and copute its contents.
	/** H 分量划分为30个等级,S分量划分为32个等级 */
	int h_bins = 30;
	int s_bins = 32;
	CvHistogram* hist;
	{
		int hist_size[] = { h_bins, s_bins };
		float h_ranges[] = { 0, 180 };        /* hue varies from 0 (~0°red) to 180 (~360°red again) */
		float s_ranges[] = { 0, 255 };         /* saturation varies from 0 (black-gray-white) to 255 (pure spectrum color) */
		float * ranges[] = { h_ranges, s_ranges };

		/* 创建直方图,二维, 每个维度上均分 */
		hist = cvCreateHist(
			2,                   // int dims  
			hist_size,        // int* sizes 
			CV_HIST_ARRAY,// int type
			ranges,            // float** ranges 
			1                     //uniform
			);
	}

	//  根据H,S两个平面数据统计直方图 
	cvCalcHist(planes, hist, 0, 0);        //Compute histogram
	//归一化处理
	cvNormalizeHist(hist, 1.0);          //Normalize it

	//Creat an image to use to visualize our histogram.
	int scale = 10;
	IplImage* hist_img = cvCreateImage(cvSize(h_bins*scale, s_bins*scale),8,3);
	cvZero(hist_img);

	//populate our visualization with litter gray squares.
	/** 获取直方图统计的最大值,用于动态显示直方图 */
	float max_value = 0;
	cvGetMinMaxHistValue(hist, 0, &max_value, 0, 0);
	for (int h = 0; h < h_bins; h++)
	{
		for (int s = 0; s < s_bins; s++)
		{
			float bin_val = cvQueryHistValue_2D(hist, h, s);
			int intensity = cvRound(bin_val * 255 / max_value);
			cvRectangle(
				hist_img,
				cvPoint(h*scale, s*scale),
				cvPoint((h + 1)*scale - 1, (s + 1)*scale - 1),
				CV_RGB(intensity, intensity, intensity),
				CV_FILLED
				);
		}
	}

	cvNamedWindow("Source", 1);
	cvShowImage("Source", src);

	cvNamedWindow("H-S Histogram", 1);
	cvShowImage("H-S Histogram", hist_img);

	cvWaitKey(0);
}


void COpenCV::OnOpencvMatchtemplate()
{
	// TODO:  在此添加命令处理程序代码
	IplImage *src, *templ, *ftmp[6];  
	int i;
	//Read in the source image to be searched;
	if ((src = cvLoadImage("D:\\19.jpg", 1)) == 0)
	{
		printf("Error on reading src image %s\n", "D:\\19.jpg");
	}
	//Read in the template to be used for matching:
	if ((templ = cvLoadImage("D:\\20.jpg", 1)) == 0)
	{
		printf("Error on reading template image %s\n", "D:\\20.jpg");
	}

	//allocate output images:
	int iwidth = src->width - templ->width + 1; 
	int iheight = src->height - templ->height + 1;
	for (i = 0; i < 6; i++)
	{
		ftmp[i] = cvCreateImage(cvSize(iwidth, iheight), 32, 1);

	}

	//Do the matching of the template witch the image:
	for (i = 0; i < 6; i++)
	{
		double min_val;
		double max_val;
		CvPoint min_loc;
		CvPoint max_loc;

		cvMatchTemplate(src, templ, ftmp[i], i);
		cvNormalize(ftmp[i], ftmp[i], 1, 0, CV_MINMAX);

		cvMinMaxLoc(ftmp[i], &min_val, &max_val, &min_loc, &max_loc, NULL);
		cvRectangle(src, cvPoint(min_loc.x, min_loc.y), cvPoint((min_loc.x + templ->width), (min_loc.y + templ->height)), CV_RGB(0, 255, 0), 1);

	}

	//Displa
	cvNamedWindow("Template", 0);
	cvShowImage("Template", templ);

	cvNamedWindow("image", 0);
	cvShowImage("image", src);

	cvNamedWindow("SQDIFF", 0);
	cvShowImage("SQDIFF", ftmp[0]);

	cvNamedWindow("SQDIFF_NORMED", 0);
	cvShowImage("SQDIFF_NORMED", ftmp[1]);

	cvNamedWindow("CCORR", 0);
	cvShowImage("CCORR", ftmp[2]);

	cvNamedWindow("CCORR_NORMED", 0);
	cvShowImage("CCORR_NORMED", ftmp[3]);

	cvNamedWindow("CCOEFF", 0);
	cvShowImage("CCOEFF", ftmp[4]);

	cvNamedWindow("CCOEFF_NORMED", 0);
	cvShowImage("CCOEFF_NORMED", ftmp[5]);
}


void COpenCV::OnOpencvContours2()
{
	// TODO:  在此添加命令处理程序代码
	cvNamedWindow("box", 0);
	IplImage* img_8uc1 = cvLoadImage("C:\\Users\\Administrator\\Desktop\\159.jpg", CV_LOAD_IMAGE_GRAYSCALE);
	IplImage* img_edge = cvCreateImage(cvGetSize(img_8uc1), 8, 1);
	IplImage* img_8uc3 = cvCreateImage(cvGetSize(img_8uc1), 8, 3);
	cvThreshold(img_8uc1, img_edge, 128, 255, CV_THRESH_BINARY);
	CvMemStorage* storage = cvCreateMemStorage();
	CvSeq* first_contours = NULL;
	int NC = cvFindContours(
		img_edge,
		storage,
		&first_contours,
		sizeof(CvContour),
		CV_RETR_LIST
		);
	int n = 0;
	printf("Total Contours Deleted:%d\n", NC);
	for (CvSeq* c = first_contours; c != NULL; c = c->h_next)
	{
		cvCvtColor(img_8uc1, img_8uc3, CV_GRAY2BGR);
		cvDrawContours(
			img_8uc3,
			c,
			cvScalarAll(255),
			cvScalarAll(255),
			100
			);

		cvShowImage("box", img_8uc3);
		for (int i = 0; i < c->total; ++i)
		{
			CvPoint* p = CV_GET_SEQ_ELEM(CvPoint, c, i);
		}

		cvWaitKey(0);
		n++;
	}

	cvCvtColor(img_8uc1, img_8uc3, CV_GRAY2BGR);
	cvShowImage("box", img_8uc3);
	cvNamedWindow("src", 0);
	cvShowImage("src", img_8uc1);
	cvNamedWindow("edge", 0);
	cvShowImage("edge", img_edge);

	cvWaitKey(0);
	cvDestroyAllWindows();
	cvReleaseImage(&img_8uc1);
	cvReleaseImage(&img_8uc3);
	cvReleaseImage(&img_edge);

}


void COpenCV::OnOpencvAddgaussiannoise()
{
	// TODO:  在此添加命令处理程序代码

	Mat image;
	image = imread("D:\\11.jpg", 1); // Read the file   

	if (!image.data) // Check for invalid input   
	{
		cout << "Could not open or find the image" << std::endl;
	}

	namedWindow("Display window", WINDOW_AUTOSIZE); // Create a window for display.   
	imshow("Display window", image); // Show our image inside it.   

	// Add Gaussian noise here   
	AddGaussian(image);

	namedWindow("Noisy image", WINDOW_AUTOSIZE); // Create a window for display.   
	imshow("Noisy image", image); // Show our image inside it.   
	waitKey(0); // Wait for a keystroke in the window   


}

void COpenCV::AddGaussian(Mat& I)
{
	// accept only char type matrices   
	CV_Assert(I.depth() != sizeof(uchar));

	int channels = I.channels();

	int nRows = I.rows;
	int nCols = I.cols * channels;

	if (I.isContinuous())
	{
		nCols *= nRows;
		nRows = 1;
	}

	int i, j;
	uchar* p;
	for (i = 0; i < nRows; ++i){
		p = I.ptr<uchar>(i);
		for (j = 0; j < nCols; ++j){
			double val = p[j] + generateGaussianNoise() * 128;
			if (val < 0)
				val = 0;
			if (val > 255)
				val = 255;

			p[j] = (uchar)val;

		}
	}

}


void COpenCV::OnOpencvTestnoise()
{
	// TODO:  在此添加命令处理程序代码


}

void COpenCV::OnOpencvCvboxpoints()
{
	// TODO:  在此添加命令处理程序代码
	//画缺陷的外接矩形
	IplImage *src = cvLoadImage("D:\\21.jpg", CV_LOAD_IMAGE_GRAYSCALE);
	CvMemStorage* storage = cvCreateMemStorage(0);
	CvSeq* contour = 0;

	cvNamedWindow("image0", 1);
	cvShowImage("image0", src);
	int   hei = src->height;
	int   wid = src->width;
	uchar *data = (uchar*)src->imageData;
	int widstep = src->widthStep;
	int channel = src->nChannels;
	IplImage *dst = cvCreateImage(cvSize(wid, hei), IPL_DEPTH_8U, 3);
	// invert the image  
	for (int i = 0; i<hei; i++)
	{
		for (int j = 0; j<wid; j++)
		{
			if (data[i*widstep + j*channel]>120)
			{
				data[i*widstep + j*channel] = 0;
			}
			else
			{
				data[i*widstep + j*channel] = 255;
			}
		}
	}

	cvNamedWindow("image", 0);
	cvShowImage("image", src);
	printf("图像的高为:%d,宽为:%d\n\n", hei, wid);
	cvCvtColor(src, dst, CV_GRAY2BGR);;
	cvFindContours(src, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
	for (; contour != 0; contour = contour->h_next)
	{
		CvBox2D rect = cvMinAreaRect2(contour, storage);
		CvPoint2D32f rect_pts0[4];
		cvBoxPoints(rect, rect_pts0);
		int npts = 4, k = 0;
		int aaa = 0, bbb = 0;
		CvPoint rect_pts[4], *pt = rect_pts;
		printf("连通区域最小外接矩形顶点坐标分别为:\n");
		for (int i = 0; i<4; i++)
		{
			rect_pts[i] = cvPointFrom32f(rect_pts0[i]);
			printf("%d %d\n", rect_pts[i].x, rect_pts[i].y);
			aaa = (int)sqrt((pow((rect_pts[0].x - rect_pts[1].x), 2) + pow((rect_pts[0].y
				- rect_pts[1].y), 2)));
			bbb = (int)sqrt((pow((rect_pts[0].x - rect_pts[3].x), 2) + pow((rect_pts[0].
				y - rect_pts[3].y), 2)));
			if (aaa<bbb)
			{
				k = aaa;
				aaa = bbb;
				bbb = k;
			}
		}
		printf("最小外接矩形的长为:%d宽为:%d。\n\n", aaa, bbb);
		cvPolyLine(dst, &pt, &npts, 1, 1, CV_RGB(255, 0, 0), 1);
	}
	cvNamedWindow("image5", 1);
	cvShowImage("image5", dst);
	cvWaitKey(0);
	cvDestroyWindow("image");
	cvDestroyWindow("image5");
	cvReleaseImage(&src);


}


void COpenCV::OnOpencv2Mythros()
{
	//获取单通道的值,并对像素进行处理
	// TODO:  在此添加命令处理程序代码
	IplImage* imgSource = cvLoadImage("C:\\Users\\Administrator\\Desktop\\no2.jpg",0);
	cvNamedWindow("Image", CV_WINDOW_AUTOSIZE);
	cvShowImage("Image", imgSource);

	if(imgSource != 0)//imgSource为IplImage*
	{
		for (int j = 0; j < imgSource->width; ++j)
		{
			for (int i = 0; i < imgSource->height; ++i)
			{
				//获取(i, j)处的单道图像像素值
				double dPixelVal = cvGetReal2D(imgSource, i, j);
				if (dPixelVal>51 && dPixelVal <= 102)
				{
					//设定(i, j)处的单通道图像像素值
					cvSetReal2D(imgSource, i, j, 51);
				}
			}
		}
	}
	cvSaveImage("C:\\Users\\Administrator\\Desktop\\no2.jpg", imgSource);
	cvWaitKey(0);
	cvDestroyWindow("Image");
	cvReleaseImage(&imgSource);
}


void COpenCV::OnOpencv2Cvavg()
{
	// TODO:  在此添加命令处理程序代码
		IplImage *src1 = cvLoadImage("C:\\Users\\Administrator\\Desktop\\no2.jpg");
		CvScalar cs,cs1;
		cvAvgSdv(src1,&cs,&cs1);    
		cout<<"平均值:"<<endl; cout<<cs.val[0] << endl;    
		cout<<cs.val[1] << endl;    
		cout<<cs.val[2] << endl;    
		cout<<cs.val[3] << endl;    
		cout <<endl;  cout <<"标准差"<<endl; 
		cout<<cs1.val[0] << endl;   
		cout<<cs1.val[1] << endl;   
		cout<<cs1.val[2] << endl;   
		cout<<cs1.val[3] << endl;   
}


void COpenCV::OnOpencvImagematching()
{
	// TODO:  在此添加命令处理程序代码
	double dbMax = 0;                                       //最大像素值  
	double dSigmaST, dSigmaS, dSigmaT;                      //中间结果  
	double   R;                                             //相似性测量  
	int   i, j, m, n;
	int  nMaxWidth, nMaxHeight;
	CvScalar  pixelSrc, pixelTem, pixel0, pixel1;

	IplImage* TemplateSrc = cvLoadImage("D:\\20.jpg");        //模板图像  
	IplImage* src = cvLoadImage("D:\\24.jpg");                //原图  

	//计算dSigmaT  
	dSigmaT = 0;
	for (n = 0; n < TemplateSrc->height; n++)
	{
		for (m = 0; m < TemplateSrc->width; m++)
		{
			pixelTem = cvGet2D(TemplateSrc, n, m);
			dSigmaT += (double)pixelTem.val[0] * pixelTem.val[0];
		}
	}

	//找到图像中最大相似性出现的位置  
	for (j = 0; j < src->height - TemplateSrc->height + 1; j++)
	{
		for (i = 0; i < src->width - TemplateSrc->width + 1; i++)
		{
			dSigmaST = 0;
			dSigmaS = 0;
			for (n = 0; n < TemplateSrc->height; n++)
			{
				for (m = 0; m < TemplateSrc->width; m++)
				{
					pixelSrc = cvGet2D(src, j + n, i + m);
					pixelTem = cvGet2D(TemplateSrc, n, m);
					dSigmaS += (double)pixelSrc.val[0] * pixelSrc.val[0];
					dSigmaST += (double)pixelSrc.val[0] * pixelTem.val[0];
				}
			}
			R = dSigmaST / (sqrt(dSigmaS)*sqrt(dSigmaT));    //计算相似性  
			if (R > dbMax)         //与最大相似性比较  
			{
				dbMax = R;
				nMaxHeight = j;
				nMaxWidth = i;
			}
		}
	}

	//对目标像素进行赋值  
	for (j = nMaxHeight; j <TemplateSrc->height + nMaxHeight; j++)
	{
		for (i = nMaxWidth; i < TemplateSrc->width + nMaxWidth; i++)
		{
			pixel0 = cvGet2D(src, j, i);
			pixel1.val[0] = pixel0.val[0] / 2;
			pixel1.val[1] = pixel0.val[1] / 2;
			pixel1.val[2] = pixel0.val[2] / 2;
			cvSet2D(src, j, i, pixel1);
		}
	}


	cvNamedWindow("White", CV_WINDOW_AUTOSIZE);
	cvShowImage("White", src);


	while (1)
	{
		if (cvWaitKey(100) == 27) break;
	}
	cvDestroyWindow("White");
	cvReleaseImage(&src);
	exit(0);
}