OpenCV Lesson 4 : Operations with images

Load an image from a file:

Mat img = imread(filename);

If you need a grayscale image:

Mat img = imread(filename, IMREAD_GRAYSCALE);

To save an image to a file:

imwrite(filename, img);

Get pixel intensity value from a single channel gray scale image(8UC1) and the pixel coordinates x and y:

Scalar intensity = img.at<uchar>(y, x);

Alternatively, you can use the following notation (C++ only):

Scalar intensity = img.at<uchar>(Point(x, y));

let us consider a 3 channel image with BGR color ordering:

Vec3b intensity = img.at<Vec3b>(y, x);
uchar blue = intensity.val[0];
uchar green = intensity.val[1];
uchar red = intensity.val[2];

For floating-point images:

Vec3f intensity = img.at<Vec3f>(y, x);
float blue = intensity.val[0];
float green = intensity.val[1];
float red = intensity.val[2];

Change pixel intensities:

img.at(y, x) = 128;

There are functions in OpenCV, especially from calib3d module, such as cv::projectPoints, that take an array of 2D or 3D points in the form of Mat. Matrix should contain exactly one column, each row corresponds to a point, matrix type should be 32FC2 or 32FC3 correspondingly. Such a matrix can be easily constructed from std::vector (C++ only):

vector<Point2f> points;
//... fill the array
Mat pointsMat = Mat(points);

A Mat keeps a reference count that tells if data has to be deallocated when a particular instance of Mat is destroyed. Here is an example of creating two matrices without copying data (C++ only):

std::vector<Point3f> points;
 // .. fill the array
Mat pointsMat = Mat(points).reshape(1);

As a result, we get a 32FC1 matrix with 3 columns instead of 32FC3 matrix with 1 column. pointsMat uses data from points and will not deallocate the memory when destroyed. In this particular instance, however, developer has to make sure that lifetime of points is longer than of pointsMat If we need to copy the data, this is done using, for example, cv::Mat::copyTo or cv::Mat::clone:

Mat img = imread("image.jpg");
Mat img1 = img.clone();

An empty output Mat can be supplied to each function. Each implementation calls Mat::create for a destination matrix. This method allocates data for a matrix if it is empty. If it is not empty and has the correct size and type, the method does nothing. If however, size or type are different from the input arguments, the data is deallocated (and lost) and a new data is allocated. For example:

Mat img = imread("image.jpg");
Mat sobelx;
Sobel(img, sobelx, CV_32F, 1, 0);

Change image type from 8UC1 to 32FC1:

src.convertTo(dst, CV_32F);

你可能感兴趣的:(OpenCV,opencv,人工智能,计算机视觉)