Read /Write Image
//Include Libraries
#include<opencv2/opencv.hpp>
#include<iostream>
// Namespace nullifies the use of cv::function();
using namespace std;
using namespace cv;
// Read an image
Mat img_grayscale = imread("test.jpg", cv2.IMREAD_GRAYSCALE);
// Display the image.
imshow("grayscale image", img_grayscale);
// Wait for a keystroke.
waitKey(0);
// Destroys all the windows created
destroyAllWindows();
// Write the image in the same directory
imwrite("grayscale.jpg", img_grayscale);
Reading Videos using OpenCV
// Include Libraries
#include<opencv2/opencv.hpp>
#include<iostream>
// Namespace to nullify use of cv::function(); syntax
using namespace std;
using namespace cv;
int main()
{
// initialize a video capture object
VideoCapture vid_capture("Resources/Cars.mp4"); // Video File
VideoCapture vid_capture("Resources/Image_sequence/Cars%04d.jpg");// From Image Sequence
// Print error message if the stream is invalid
if (!vid_capture.isOpened())
{
cout << "Error opening video stream or file" << endl;
}
else
{
// Obtain fps and frame count by get() method and print
// You can replace 5 with CAP_PROP_FPS as well, they are enumerations
int fps = vid_capture.get(5);
cout << "Frames per second :" << fps;
// Obtain frame_count using opencv built in frame count reading method
// You can replace 7 with CAP_PROP_FRAME_COUNT as well, they are enumerations
int frame_count = vid_capture.get(7);
cout << " Frame count :" << frame_count;
}
// Read the frames to the last frame
while (vid_capture.isOpened())
{
// Initialise frame matrix
Mat frame;
// Initialize a boolean to check if frames are there or not
bool isSuccess = vid_capture.read(frame);
// If frames are present, show it
if(isSuccess == true)
{
//display frames
imshow("Frame", frame);
}
// If frames are not there, close it
if (isSuccess == false)
{
cout << "Video camera is disconnected" << endl;
break;
}
//wait 20 ms between successive frames and break the loop if key q is pressed
int key = waitKey(20);
if (key == 'q')
{
cout << "q key is pressed by the user. Stopping the video" << endl;
break;
}
}
// Release the video capture object
vid_capture.release();
destroyAllWindows();
return 0;
}
Writing Videos using OpenCV
Here’s the syntax for VideoWriter()
:
VideoWriter(filename, apiPreference, fourcc, fps, frameSize[, isColor])
The VideoWriter()
class takes the following arguments:
-
filename
: pathname for the output video file -
apiPreference
: API backends identifier -
fourcc
: 4-character code of codec, used to compress the frames (fourcc) -
fps
: Frame rate of the created video stream -
frame_size
: Size of the video frames -
isColor
: If not zero, the encoder will expect and encode color frames. Else it will work with grayscale frames (the flag is currently supported on Windows only).
视频编解码器指定如何压缩视频流。它将未压缩的视频转换为压缩格式,反之亦然。创建AVI或MP4格式,使用以下fourcc规格:
AVI: cv2.VideoWriter_fourcc('M','J','P','G')
MP4: cv2.VideoWriter_fourcc(*'XVID')
//Initialize video writer object
VideoWriter output("Resources/output.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'),frames_per_second, frame_size);
while (vid_capture.isOpened())
{
// Initialize frame matrix
Mat frame;
// Initialize a boolean to check if frames are there or not
bool isSuccess = vid_capture.read(frame);
// If frames are not there, close it
if (isSuccess == false)
{
cout << "Stream disconnected" << endl;
break;
}
// If frames are present
if(isSuccess == true)
{
//display frames
output.write(frame);
// display frames
imshow("Frame", frame);
// wait for 20 ms between successive frames and break
// the loop if key q is pressed
int key = waitKey(20);
if (key == ‘q’)
{
cout << "Key q key is pressed by the user.
Stopping the video" << endl;
break;
}
}
}
// Release the objects
vid_capture.release();
output.release();
Image Resizing with OpenCV
当调整图像大小:
- 重要的是要记住原始图像的纵横比(即宽度,高度),如果你想保持相同大小的图像
- 减少图片的大小需要重新采样的像素
- 增加一个图像的大小需要重建的图像。这意味着您需要插入新的像素
各种插值技术发挥作用来完成这些操作。选择通常取决于特定的应用。
- resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])
- src: It is the required input image, it could be a string with the path of the input image (eg: ‘test_image.png’).
- dsize: It is the desired size of the output image, it can be a new height and width.
- fx: Scale factor along the horizontal axis.
- fy: Scale factor along the vertical axis.
- interpolation: It gives us the option of different methods of resizing the image.
int main()
{
// Read the image using imread function
Mat image = imread("image.jpg");
imshow("Original Image", image);
// let's downscale the image using new width and height
int down_width = 300;
int down_height = 200;
Mat resized_down;
//resize down
resize(image, resized_down, Size(down_width, down_height), INTER_LINEAR);
// let's upscale the image using new width and height
int up_width = 600;
int up_height = 400;
Mat resized_up;
//resize up
resize(image, resized_up, Size(up_width, up_height), INTER_LINEAR);
// Display Images and press any key to continue
imshow("Resized Down by defining height and width", resized_down);
waitKey();
imshow("Resized Up image by defining height and width", resized_up);
waitKey();
//Resize Using Scale factor
// Scaling Up the image 1.2 times by specifying both scaling factors
double scale_up_x = 1.2;
double scale_up_y = 1.2;
// Scaling Down the image 0.6 times specifying a single scale factor.
double scale_down = 0.6;
Mat scaled_f_up, scaled_f_down;
//resize
resize(image,scaled_f_down, Size(), scale_down, scale_down, INTER_LINEAR);
resize(image, scaled_f_up, Size(), scale_up_x, scale_up_y, INTER_LINEAR);
destroyAllWindows();
return 0;
}
合并图像为一张
Mat a,b,c;
vconcat(res_inter_linear, res_inter_nearest, a);
vconcat(res_inter_area, res_inter_area, b);
vconcat(a, b, c);
// Display the image Press any key to continue
imshow("Inter Linear :: Inter Nearest :: Inter Area :: Inter Area", c);
Cropping an Image using OpenCV
int main()
{
// Read image
Mat img = imread("test.jpg");
cout << "Width : " << img.size().width << endl;
cout << "Height: " << img.size().height << endl;
cout<<"Channels: :"<< img.channels() << endl;
// Crop image
// img(Range(start_row, end_row), Range(start_col, end_col))
Mat cropped_image = img(Range(80,280), Range(150,330));
//display image
imshow(" Original Image", img);
imshow("Cropped Image", cropped_image);
//Save the cropped Image
imwrite("Cropped Image.jpg", cropped_image);
// 0 means loop infinitely
waitKey(0);
destroyAllWindows();
return 0;
}
将图像分切为拼图类似

int M = 76;
int N = 104;
int x1 = 0;
int y1 = 0;
for (int y = 0; y<imgheight; y=y+M)
{
for (int x = 0; x<imgwidth; x=x+N)
{
if ((imgheight - y) < M || (imgwidth - x) < N)
{
break;
}
y1 = y + M;
x1 = x + N;
string a = to_string(x);
string b = to_string(y);
if (x1 >= imgwidth && y1 >= imgheight)
{
x = imgwidth - 1;
y = imgheight - 1;
x1 = imgwidth - 1;
y1 = imgheight - 1;
// crop the patches of size MxN
Mat tiles = image_copy(Range(y, imgheight), Range(x, imgwidth));
//save each patches into file directory
imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);
rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);
}
else if (y1 >= imgheight)
{
y = imgheight - 1;
y1 = imgheight - 1;
// crop the patches of size MxN
Mat tiles = image_copy(Range(y, imgheight), Range(x, x+N));
//save each patches into file directory
imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);
rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);
}
else if (x1 >= imgwidth)
{
x = imgwidth - 1;
x1 = imgwidth - 1;
// crop the patches of size MxN
Mat tiles = image_copy(Range(y, y+M), Range(x, imgwidth));
//save each patches into file directory
imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);
rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);
}
else
{
// crop the patches of size MxN
Mat tiles = image_copy(Range(y, y+M), Range(x, x+N));
//save each patches into file directory
imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);
rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);
}
}
}
图像旋转&平移
旋转操作一般分为三步
- 获取旋转中心,通常是图像的中心
- 计算旋转矩阵:getRotationMatrix2D()
- 执行变换操作:warpAffine()
getRotationMatrix2D(center, angle, scale)
center
: the center of rotation for the input image
angle
: the angle of rotation in degrees:正数-逆时针
scale
: an isotropic scale factor that scales the image up or down according to the value provided
warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]])
The following are the arguments of the function:
src
: the source mage
M
: the transformation matrix
dsize
: size of the output image
dst
: the output image
flags
: combination of interpolation methods such as INTER_LINEAR or INTER_NEAREST
borderMode
: the pixel extrapolation method
borderValue
: the value to be used in case of a constant border, has a default value of 0
平移操作:
In computer vision, translation of an image means shifting it by a specified number of pixels, along the x and y axes. Let the pixels by which the image needs to shifted be tx
and ty
. Then you can define a translation matrix M

Now, there are a few points you should keep in mind while shifting the image by tx
and ty
values.
-
tx
正数 向右平移. -
ty
正数 向下平移
int main(int, char**)
{
Mat image = imread("image.jpg");
imshow("image", image);
waitKey(0);
double angle = 45;
// get the center coordinates of the image to create the 2D rotation matrix
Point2f center((image.cols - 1) / 2.0, (image.rows - 1) / 2.0);
// using getRotationMatrix2D() to get the rotation matrix
Mat rotation_matix = getRotationMatrix2D(center, angle, 1.0);
// we will save the resulting image in rotated_image matrix
Mat rotated_image;
// rotate the image using warpAffine
warpAffine(image, rotated_image, rotation_matix, image.size());
imshow("Rotated image", rotated_image);
// 平移
// get tx and ty values for translation
float tx = float(width) / 4;
float ty = float(height) / 4;
// create the translation matrix using tx and ty
float warp_values[] = { 1.0, 0.0, tx, 0.0, 1.0, ty };
Mat translation_matrix = Mat(2, 3, CV_32F, warp_values);
return 0;
}
给图片上做标记:注释,绘制图形等

网友评论