cvtColor(src, src_gray, CV_BGR2GRAY)报错
利用cvtColor 进行灰度转换时,不能将 灰度图 转为灰度图,所以在转换前,需对原始图像进行判断。
将这个改成以下
int main(int argc, char* argv[]) { Mat m = imread("2.jpg", CV_LOAD_IMAGE_COLOR); IplImage src(m); cvNamedWindow("showImage"); IplImage* gimg = cvCreateImage(cvGetSize(&src), 8, 1); cvCvtColor(&src, gimg, CV_BGR2GRAY); cvSaveImage("1.jpg", gimg); cvShowImage("showImage", gimg); cvWaitKey(0); cvReleaseImage(&gimg); cvDestroyWindow("showImage"); return 0; }
完整代码:
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace cv; using namespace std; /// Global variables Mat src, src_gray; int thresh = 200; int max_thresh = 255; char* source_window = "Source image"; char* corners_window = "Corners detected"; /// Function header void cornerHarris_demo(int, void*); void cvtColor_src(Mat &src, Mat &dst); /** @function main */ int main(int argc, char** argv) { /// Load source image and convert it to gray src = imread("E:\\VS2015Opencv\\vs2015\\project\\picture\\06.jpg"); // 转换单通道 cvtColor_src(src,src_gray); /// Create a window and a trackbar namedWindow(source_window, CV_WINDOW_AUTOSIZE); createTrackbar("Threshold: ", source_window, &thresh, max_thresh, cornerHarris_demo); imshow(source_window, src); cornerHarris_demo(0, 0); waitKey(0); return(0); } void cvtColor_src(Mat &src, Mat &src_gray) { // 转换单通道 if (src.channels() == 4) { cv::cvtColor(src, src_gray, CV_BGRA2GRAY); } else if (src.channels() == 3) { cv::cvtColor(src, src_gray, CV_BGR2GRAY); } else if (src.channels() == 2) { cv::cvtColor(src, src_gray, CV_BGR5652GRAY); } else if (src.channels() == 1) {// 单通道的图片直接就不需要处理 src_gray = src; } else { // 负数,说明图有问题 直接返回 src_gray = src; } } /** @function cornerHarris_demo */ void cornerHarris_demo(int, void*) { Mat dst, dst_norm, dst_norm_scaled; dst = Mat::zeros(src.size(), CV_32FC1); /// Detector parameters int blockSize = 2; int apertureSize = 3; double k = 0.04; /// Detecting corners cornerHarris(src_gray, dst, blockSize, apertureSize, k, BORDER_DEFAULT); /// Normalizing normalize(dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat()); convertScaleAbs(dst_norm, dst_norm_scaled); /// Drawing a circle around corners for (int j = 0; j < dst_norm.rows; j++) { for (int i = 0; i < dst_norm.cols; i++) { if ((int)dst_norm.at<float>(j, i) > thresh) { circle(dst_norm_scaled, Point(i, j), 5, Scalar(0), 2, 8, 0); } } } /// Showing the result namedWindow(corners_window, CV_WINDOW_AUTOSIZE); imshow(corners_window, dst_norm_scaled); }