Tạo 1 project Win32 console và chép code sau:
#include <iostream> #include <opencv2\opencv.hpp>#include <opencv2\highgui\highgui.hpp> using namespace std;
using namespace cv;
void main() { // Load ảnh cần chuyển IplImage* img = cvLoadImage("pic1.jpg",1); // Tạo một biến mới để chuyển ảnh màu thành xem // cvGetSize(img) : lấy thông tin kích thước của img, IPL_DEPTH_8U là chuẩn màu của hình.IplImage* grayimg = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1);
// Lấy thông tin chiều dài, rộng, số kênh màu, widthStep, int nl= img->height; int nc= img->width * img->nChannels; int step= img->widthStep; int graystep = grayimg->widthStep; // img -> imageData: mảng chứa các mã màu của imguchar *data= (uchar *)img->imageData;
uchar *graydata= (uchar *)grayimg->imageData;
for (int i=0; i < nl; i++) {
for (int j=0; j < nc; j += img->nChannels) {
// Công thức chuyển anh RGB thành màu GRAY.graydata[(int)j/3]= (unsigned char) (0.299*data[j + 0] + 0.587*data[j + 1] + 0.114*data[j+2] + 0.5);
}
data+= step;
graydata+=graystep;
}
// Mở và hiển thị ảnh vừa chuyển cvNamedWindow("Xam",0); cvShowImage("Xam",grayimg);waitKey(0);
// Giải phóng vùng nhớ cvDestroyWindow("Xam");cvReleaseImage(&img);
cvReleaseImage(&grayimg);
}