#include "iostream"
#include "cv.h"
#include "highgui.h"
#include "cvaux.h"
#include "cxmisc.h"
#include "math.h"
using namespace cv;
using namespace std;
int main(){
int height, width, x, y, i, minX, minY, maxX, maxY;
char imgFileName[100];
IplImage *origImage = cvLoadImage("BaybayinMark/b9.jpg", -1);
height = origImage->height;
width = origImage->width;
IplImage *grayImage = cvCreateImage(cvSize(width, height), 8, 1);
IplImage *binImage = cvCreateImage(cvSize(width, height), 8, 1);
//Pre-processing phase
cvCvtColor(origImage, grayImage, CV_BGR2GRAY);
cvDilate(grayImage, grayImage, NULL, 1);
cvSmooth(grayImage, grayImage, CV_GAUSSIAN, 21, 21, 0, 0);
cvThreshold(grayImage, binImage, 120, 255, CV_THRESH_BINARY);
cvNormalize(binImage,binImage,0,1,CV_MINMAX);
minX = width;
minY = height;
maxX = 0;
maxY = 0;
CvScalar s;
for (x=0; x<width-1; x++){
for(y=0; y<height-1; y++){
s = cvGet2D(binImage, y, x);
//printf("%f\n", s.val[0]);
if (s.val[0] == 1){
//printf("HELLO");
minX = min(minX, x);
minY = min(minY, y);
maxX = max(maxX, x);
maxY = max(maxY, y);
}
}
}
cvSetImageROI(binImage, cvRect(minX, minY, maxX-minX, maxY-minY));
IplImage *cropImage = cvCreateImage(cvGetSize(binImage), 8, 1);
cvCopy(binImage, cropImage, NULL);
cvSaveImage("crop/cropImage9.jpg", cropImage);
cvResetImageROI(binImage);
cvReleaseImage(&origImage);
cvReleaseImage(&binImage);
cvReleaseImage(&grayImage);
cvReleaseImage(&cropImage);
}
嗨!我只是想问一下这段代码。我试图识别图像的最外边缘并根据它们裁剪图像。我跑完后所有的都是一个大小相同的黑色图像。我试图以错误的方式做到这一点吗?请告诉我,我是OpenCV的初学者。
答案 0 :(得分:12)
在急于找到 -the-heck-is-the-problem 时,人们往往会忘记一个更重要的问题:< STRONG> 如何 -the-赫克-DO-我找到的最问题的。
对于图像处理应用程序,OpenCV中的poor man's debugger可以回答如何,通过代码添加cvSaveImage()
次调用能够看到方式的每一步都在做什么:
//Pre-processing phase
cvCvtColor(origImage, grayImage, CV_BGR2GRAY);
cvSaveImage("cv_color.jpg", grayImage);
cvDilate(grayImage, grayImage, NULL, 1);
cvSaveImage("cv_dilate.jpg", grayImage);
cvSmooth(grayImage, grayImage, CV_GAUSSIAN, 21, 21, 0, 0);
cvSaveImage("cv_smooth.jpg", grayImage);
cvThreshold(grayImage, binImage, 120, 255, CV_THRESH_BINARY);
cvSaveImage("cv_threshold.jpg", binImage);
cvNormalize(binImage,binImage,0,1,CV_MINMAX);
cvSaveImage("cv_normalize.jpg", binImage);
此代码显示,即使在您的自定义for
循环之前,生成的图像也会变黑,而对此负责的调用是cvNormalize()
。但这有道理吗?您正在将[0..255]范围内的像素转换为0和1的值。
所以问题在于,在处理结束时,当您将生成的图像保存到dislk时,您忘记将值标准化回原始范围:
IplImage *cropImage = cvCreateImage(cvGetSize(binImage), 8, 1);
cvCopy(binImage, cropImage, NULL);
cvNormalize(cropImage, cropImage, 0, 255, CV_MINMAX);
cvSaveImage("result.jpg", cropImage);
这解决了这个问题。