Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ OpenCV Basic Operations

C++ OpenCV Basic Operations

Basic image operations

Reading, displaying, and saving images

In OpenCV, basic image operations include reading, displaying, and saving images. These operations are the foundation of image processing.

Read an image: When usingimreadfunction reads an image. The first parameter of this function is the path to the image file, and the second parameter is the way to read the image (such as color image, grayscale image, etc.).


cv::Mat image = cv::imread("image.jpg", cv::IMREAD_COLOR);

Displays an image: When usingimshowfunction displays an image. The first parameter of this function is the window name, and the second parameter is the image to display.


cv::imshow("Display Window", image);
cv::waitKey(0); // 等待按键按下

Save the image

: When using

imwrite

function saves an image. The first parameter of this function is the save file path, and the second parameter is the image to save.


cv::imwrite("output.jpg", image);

Basic image attributes

Basic image attributes include size, number of channels, and pixel values.

Size: the size of an image can be obtained throughrowsandcolsproperty.


int height = image.rows;
int width = image.cols;

Number of channels: the number of channels of an image can be obtained throughchannels()method.


int channels = image.channels();

Pixel values: You can dynamically bindatmethod to access image pixel values.


cv::Vec3b pixel = image.at(y, x); // 访问(x, y)处的像素值

Image creation and initialization

can be used viaMatclass to create and initialize images.

Create an image: can create an image of a specified size and type.


cv::Mat newImage(480, 640, CV_8UC3, cv::Scalar(0, 0, 255)); // 创建一个640x480的红色图像

Initialize an image: You can usesetTomethod to initialize an image.


image.setTo(cv::Scalar(255, 255, 255)); // 将图像初始化为白色

Image pixel operations

Image pixel operations include traversing pixels and modifying pixel values.

Traverse pixels: you can use a double loop to traverse every pixel of the image.


for (int y = 0; y < image.rows; y++) {
    for (int x = 0; x < image.cols; x++) {
        cv::Vec3b& pixel = image.at(y, x);
        // Operate on pixels
    }
}

Modify pixel values: you can directly modify the value of a pixel.

pixel[0] = 255; // 将蓝色通道设置为255
pixel[1] = 0;   // 将绿色通道设置为0
pixel[2] = 0;   // 将红色通道设置为0

Geometric transformations of images

Scaling, rotation, translation, flipping

Geometric transformations of images include scaling, rotation, translation, and flipping.

Scaling: When usingresizefunction scales an image.


cv::Mat resizedImage;
cv::resize(image, resizedImage, cv::Size(newWidth, newHeight));

Rotate: When usinggetRotationMatrix2DandwarpAffinefunction rotates an image.


cv::Point2f center(image.cols / 2.0, image.rows / 2.0);
cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, angle, 1.0);
cv::Mat rotatedImage;
cv::warpAffine(image, rotatedImage, rotationMatrix, image.size());

Translation: When usingwarpAffinefunction translates an image.


cv::Mat translationMatrix = (cv::Mat_(2, 3) << 1, 0, tx, 0, 1, ty);
cv::Mat translatedImage;
cv::warpAffine(image, translatedImage, translationMatrix, image.size());

Flipping: When usingflipfunction flips an image.


cv::Mat flippedImage;
cv::flip(image, flippedImage, 1); // 1表示水平翻转,0表示垂直翻转

Affine and perspective transformations

Affine transformation: an affine transformation is a linear transformation plus translation, which can usewarpAffinefunction.

cv::Mat affineMatrix = cv::getAffineTransform(srcPoints, dstPoints);
cv::Mat affineImage;
cv::warpAffine(image, affineImage, affineMatrix, image.size());

Perspective transformation: a perspective transformation is a more general transformation, which can usewarpPerspectivefunction.


cv::Mat perspectiveMatrix = cv::getPerspectiveTransform(srcPoints, dstPoints);
cv::Mat perspectiveImage;
cv::warpPerspective(image, perspectiveImage, perspectiveMatrix, image.size());

Image color space conversion

RGB, grayscale, HSV and other color spaces

Image color spaces include RGB, grayscale, and HSV, among others.

Color space conversion

Use cvtColor function to perform color space conversion.

RGB to grayscale:


cv::Mat grayImage;
cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY);

RGB to HSV:


cv::Mat hsvImage;
cv::cvtColor(image, hsvImage, cv::COLOR_BGR2HSV);

Channel splitting and merging

Channel splitting: When usingsplitfunction splits the channels of an image.


std::vector channels;
cv::split(image, channels);

Channel merging: When usingmergefunction merges multiple channels into one image.


cv::Mat mergedImage;
cv::merge(channels, mergedImage);

Example

C++ OpenCV basic operations include image reading, displaying, saving, pixel operations, image attribute retrieval, etc.

Below are some common OpenCV basic operations and their code examples:

1. Reading and displaying images

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

// Check if the image loaded successfully

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// display the image

    namedWindow

(

"Display Image"

, WINDOW_AUTOSIZE

)

;

    imshow

(

"Display Image"

, image

)

;

   

// Wait for a key press

    waitKey

(

0

)

;

   

// close the window

    destroyAllWindows

(

)

;

   

return

0

;

}

2. Saving images

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// save the image

   

bool

isSaved

=

imwrite

(

"saved_image.jpg"

, image

)

;

   

if

(

isSaved

)

{

       

cout

<<

"Image saved successfully!"

<<

endl

;

   

}

else

{

       

cout

<<

"Image save failed!"

<<

endl

;

   

}

   

return

0

;

}

3. Getting image attributes

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// get image attributes

   

int

width

=

image.

cols

;

 

// image width

   

int

height

=

image.

rows

;

// image height

   

int

channels

=

image.

channels

(

)

;

// number of image channels

   

cout

<<

"Image width: "

<<

width

<<

endl

;

   

cout

<<

"Image height: "

<<

height

<<

endl

;

   

cout

<<

"Image channels: "

<<

channels

<<

endl

;

   

return

0

;

}

4. Accessing and modifying pixel values

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// access pixel values (BGR format)

    Vec3b pixel

=

image.

at

<
Vec3b
(
100
,
100
)

;

// get the pixel value at position (100, 100)

   

cout

<<

"B: "

<<

(

int

)

pixel

[

0

]

<<

", G: "

<<

(

int

)

pixel

[

1

]

<<

", R: "

<<

(

int

)

pixel

[

2

]

<<

endl

;

   

// modify the pixel value

    image.

at

<
Vec3b
(
100
,
100
)
=
Vec3b
(
255
,
0
,
0
)

;

// set the pixel at position (100, 100) to blue

   

// display the modified image

    imshow

(

"Modified Image"

, image

)

;

    waitKey

(

0

)

;

    destroyAllWindows

(

)

;

   

return

0

;

}

5. Image color space conversion

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// convert to grayscale image

    Mat grayImage

;

    cvtColor

(

image, grayImage, COLOR_BGR2GRAY

)

;

   

// display the grayscale image

    imshow

(

"Gray Image"

, grayImage

)

;

    waitKey

(

0

)

;

    destroyAllWindows

(

)

;

   

return

0

;

}

6. Image cropping and scaling

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// crop the image

    Rect roi

(

100

,

100

,

200

,

200

)

;

// (x, y, width, height)

    Mat croppedImage

=

image

(

roi

)

;

   

// scale the image

    Mat resizedImage

;

    resize

(

image, resizedImage, Size

(

400

,

400

)

)

;

// scale to 400x400

   

// display the cropped and scaled image

    imshow

(

"Cropped Image"

, croppedImage

)

;

    imshow

(

"Resized Image"

, resizedImage

)

;

    waitKey

(

0

)

;

    destroyAllWindows

(

)

;

   

return

0

;

}

7. Image copying and cloning

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// copy the image

    Mat copiedImage

=

image.

clone

(

)

;

   

// modify the copied image

    circle

(

copiedImage, Point

(

100

,

100

)

,

50

, Scalar

(

0

,

255

,

0

)

,

2

)

;

// draw a circle on the copied image

   

// display the original and modified images

    imshow

(

"Original Image"

, image

)

;

    imshow

(

"Copied Image"

, copiedImage

)

;

    waitKey

(

0

)

;

    destroyAllWindows

(

)

;

   

return

0

;

}

8. Geometric transformations of images

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"test.jpg"

)

;

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// rotate the image

    Mat rotatedImage

;

    Point2f center

(

image.

cols

/

2

, image.

rows

/

2

)

;

// rotation center

   

double

angle

=

45

;

// Rotation angle

   

double

scale

=

1.0

;

// scale ratio

    Mat rotationMatrix

=

getRotationMatrix2D

(

center, angle, scale

)

;

    warpAffine

(

image, rotatedImage, rotationMatrix, image.

size

(

)

)

;

   

// display the rotated image

    imshow

(

"Rotated Image"

, rotatedImage

)

;

    waitKey

(

0

)

;

    destroyAllWindows

(

)

;

   

return

0

;

}