This source file includes following definitions.
- help
- main
#include <stdio.h>
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/utility.hpp>
using namespace cv;
using namespace std;
static void help()
{
cout <<
"\nThis program shows how to use cv::Mat and IplImages converting back and forth.\n"
"It shows reading of images, converting to planes and merging back, color conversion\n"
"and also iterating through pixels.\n"
"Call:\n"
"./image [image-name Default: ../data/lena.jpg]\n" << endl;
}
#define DEMO_MIXED_API_USE 1
#ifdef DEMO_MIXED_API_USE
# include <opencv2/highgui/highgui_c.h>
# include <opencv2/imgcodecs/imgcodecs_c.h>
#endif
int main( int argc, char** argv )
{
help();
const char* imagename = argc > 1 ? argv[1] : "../data/lena.jpg";
#if DEMO_MIXED_API_USE
Ptr<IplImage> iplimg(cvLoadImage(imagename));
if(!iplimg)
{
fprintf(stderr, "Can not load image %s\n", imagename);
return -1;
}
Mat img = cv::cvarrToMat(iplimg);
#else
Mat img = imread(imagename);
if(img.empty())
{
fprintf(stderr, "Can not load image %s\n", imagename);
return -1;
}
#endif
if( img.empty() )
return -1;
Mat img_yuv;
cvtColor(img, img_yuv, COLOR_BGR2YCrCb);
vector<Mat> planes;
split(img_yuv, planes);
#if 1
MatIterator_<uchar> it = planes[0].begin<uchar>(), it_end = planes[0].end<uchar>();
for(; it != it_end; ++it)
{
double v = *it*1.7 + rand()%21-10;
*it = saturate_cast<uchar>(v*v/255.);
}
for( int y = 0; y < img_yuv.rows; y++ )
{
uchar* Uptr = planes[1].ptr<uchar>(y);
for( int x = 0; x < img_yuv.cols; x++ )
{
Uptr[x] = saturate_cast<uchar>((Uptr[x]-128)/2 + 128);
uchar& Vxy = planes[2].at<uchar>(y, x);
Vxy = saturate_cast<uchar>((Vxy-128)/2 + 128);
}
}
#else
Mat noise(img.size(), CV_8U);
randn(noise, Scalar::all(128), Scalar::all(20));
GaussianBlur(noise, noise, Size(3, 3), 0.5, 0.5);
const double brightness_gain = 0;
const double contrast_gain = 1.7;
#if DEMO_MIXED_API_USE
IplImage cv_planes_0 = planes[0], cv_noise = noise;
cvAddWeighted(&cv_planes_0, contrast_gain, &cv_noise, 1, -128 + brightness_gain, &cv_planes_0);
#else
addWeighted(planes[0], contrast_gain, noise, 1, -128 + brightness_gain, planes[0]);
#endif
const double color_scale = 0.5;
planes[1].convertTo(planes[1], planes[1].type(), color_scale, 128*(1-color_scale));
planes[2] = Mat_<uchar>(planes[2]*color_scale + 128*(1-color_scale));
planes[0] = planes[0].mul(planes[0], 1./255);
#endif
merge(planes, img_yuv);
cvtColor(img_yuv, img, COLOR_YCrCb2BGR);
namedWindow("image with grain", WINDOW_AUTOSIZE);
#if DEMO_MIXED_API_USE
cvShowImage("image with grain", iplimg);
#else
imshow("image with grain", img);
#endif
waitKey();
return 0;
}