opencv实现“找茬”

// 111.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include <iostream>
#include <cv.h>
#include <highgui.h>
using namespace std;

#define CVX_RED CV_RGB(0xff,0x00,0x00)
#define CVX_BLUE CV_RGB(0x00,0x00,0xff)//定义宏,轮廓边框颜色

int main()
{
	IplImage *img = cvLoadImage("D:\\3.bmp");
	CvScalar pixel;
	int p = 0,q,w,s;
	for (int i = 0; i < (img->width)/2; ++i)
    {
		q = 0;
		for (int j = 0; j < img->height; ++j)
        {
            pixel = cvGet2D(img, j, i);
			if((pixel.val[0] == 255) && (pixel.val[1] == 255) && (pixel.val[2] == 255))
			   q++;
        }
		if(q == img->height)
		{
			p = i;
			break;
		}
    }
	w =img->width - p;
	IplImage *img_2 = cvCreateImage(cvSize(p, img->height), IPL_DEPTH_8U, 3);
	IplImage *img_3 = cvCreateImage(cvSize(p, img->height), IPL_DEPTH_8U, 3);
	IplImage *img_4 = cvCreateImage(cvSize(p, img->height), IPL_DEPTH_8U, 3);
	for (int i = 0; i < img->height; ++i)
    {
		for (int j = 0; j < p; ++j)
        {
            pixel = cvGet2D(img, i, j);
            cvSet2D(img_2, i, j, pixel);
        }
    }
	for (int i = 0; i < img->height; ++i)
    {
		for (int j = w; j < img->width; ++j)
        {
            pixel = cvGet2D(img, i, j);
            cvSet2D(img_3, i, j - w, pixel);
        }
    }//分割图像

	cvAbsDiff(img_2,img_3,img_4);//图像做差值,结果保存

	cvErode(img_4,img_4,NULL,1);
	cvDilate(img_4,img_4,NULL,1);//腐蚀膨胀图像,消噪

	IplImage *img_5 = cvCreateImage(cvSize(p,img->height), IPL_DEPTH_8U, 1);
	IplImage *img_6 = cvCreateImage(cvSize(p,img->height), IPL_DEPTH_8U, 1);
	IplImage *img_7 = cvCreateImage(cvSize(p,img->height), IPL_DEPTH_8U, 1);

	cvCvtColor(img_4,img_5,CV_BGR2GRAY);
	cvThreshold(img_5,img_6,45,255,CV_THRESH_BINARY);//将差值彩色图像转化为灰度二值图像

	CvMemStorage *g_storage = cvCreateMemStorage(0);
	CvSeq *contours = NULL;
	cvFindContours(img_6,g_storage,&contours,sizeof(CvContour),CV_RETR_LIST);
	cvDrawContours(img_7,contours,CVX_RED,CVX_BLUE,1,2,8);//读取轮廓并输出在图像中

	printf("Contours include  %d elements:\n",contours->total);
	for(int i=0;i<contours->total;i++)
	{
		CvPoint *p = (CvPoint*)cvGetSeqElem(contours,i);
		printf("    (%d,%d)\n",p->x,p->y);
	}//输出轮廓坐标

	cvNamedWindow("image7", CV_WINDOW_AUTOSIZE);
    cvShowImage("image7", img_7);
    cvWaitKey(0);//显示轮廓图像

	cvDestroyWindow("image2");
	cvDestroyWindow("image3");
    cvDestroyWindow("image4");
	cvDestroyWindow("image5");
	cvDestroyWindow("image6");
	cvDestroyWindow("image7");
    cvReleaseImage(&img);
	cvReleaseImage(&img_2);
	cvReleaseImage(&img_3);
	cvReleaseImage(&img_4);
	cvReleaseImage(&img_5);
	cvReleaseImage(&img_6);
	cvReleaseImage(&img_7);

	return 0;
}

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页