我有以下代码。我在应用连接组件代码后使用了它,我从连接组件中获得了想要的结果,但我正在尝试使用以下代码来删除基于阈值的非常小或非常高的标签。但每次我调试它时,我都有异常..所以有人能帮我吗这是连接的组件代码
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
#define PIXEL(img,x,y) (img)->imageData[(x)*img->widthStep+(y)]
#include <iostream>
int main()
{
IplImage *GrayImg,*outImg;
GrayImg=cvLoadImage("Gray_Image.jpg",0);
if(!GrayImg){
printf("Could not load image file: %s\n");
cvWaitKey(0);
exit(0);
}
cvThreshold(GrayImg, GrayImg, 180, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);//converting image to binary
int height,width,channels;
height = GrayImg->height;
width = GrayImg->width;
channels = GrayImg->nChannels;
printf("Processing a %dx%d image with %d channels \n",height,width,channels);
outImg = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
cvZero(outImg);
//cvCopyImage(GrayImg,OutImg);
int i,j,v;
int top,left;
int topL,leftL;
int label=0;
int eq[10000][2];
int eqlength = 1;
cvNamedWindow("Gray", CV_WINDOW_AUTOSIZE);
cvShowImage("Gray", GrayImg );
for (i=0;i<height;i++) {
for (j=0;j<width;j++) {
v = (unsigned char) PIXEL(GrayImg,i,j);// cvGet2D(GrayImg,i,j).val[0];
//unsigned char v1 = PIXEL(GrayImg,i,j);
//int v2 = PIXEL(GrayImg,i,j);
//int v3 = v1;
if (v==255) {
if (i>0) top = cvGet2D(GrayImg,i-1,j).val[0];
else top = 0;
if (j>0) left = cvGet2D(GrayImg,i,j-1).val[0] ;
else left=0;
if (top==0 && left==0)
{
PIXEL(outImg,i,j) = label;
label+=1;
}
else if (top==255 && left==0) {
PIXEL(outImg,i,j) = PIXEL(outImg,i-1,j);
}
else if (top==0 && left==255) {
PIXEL(outImg,i,j) = PIXEL(outImg,i,j-1);
}
else if (top==255 && left==255) {
PIXEL(outImg,i,j) = PIXEL(outImg,i,j-1);
if (PIXEL(outImg,i-1,j) != PIXEL(outImg,i,j-1)){
if (eq[eqlength-1][0] == PIXEL(outImg,i-1,j) && eq[eqlength-1][1] == PIXEL(outImg,i,j-1)) ;
else
{
eq[eqlength][0] = PIXEL(outImg,i-1,j);
eq[eqlength][1] = PIXEL(outImg,i,j-1);
eqlength++;
}
}
}
}
}
//cvWaitKey(0);
//cvShowImage("Out", outImg);
}
int e;
for (i=0;i<height;i++)
for (j=0;j<width;j++)
if (PIXEL(outImg,i,j)!=0)
for (e=1;e<eqlength;e++)
if (PIXEL(outImg,i,j)==eq[e][0])
PIXEL(outImg,i,j)=eq[e][1];
cvNamedWindow("Out", CV_WINDOW_AUTOSIZE);
cvShowImage("Out", outImg);
这是我为删除不需要的标签而添加的代码
int* arr = new int [N];
//cout<<endl<<arr[0];
for (i=0;i<height;i++)
{
for (j=0;j<width;j++)
{
id=(unsigned char)PIXEL(outImg,i,j);
arr[id]++;
}
}
for (i=0;i<=N;i++)
{
if (arr[i]<5 || arr[i]>50)
arr[i]=0;
}
for (i=0;i<outImg->height;i++)
{
for (j=0;j<outImg->width;j++)
{
id=(unsigned char)PIXEL(outImg,i,j);
//id=cvGet2D(outImg,i,j).val[0];
if (arr[id]==0)
PIXEL(outImg,i,j)=0;
else
PIXEL(outImg,i,j)=255;
}
}
delete [] arr;
cvNamedWindow("CC", CV_WINDOW_AUTOSIZE);
cvShowImage("CC", outImg);
cvWaitKey(0);
/* Free memory and get out */
cvDestroyWindow("Gray");
cvReleaseImage(&GrayImg);
return 0;
}