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

C++ OpenCV Advanced Image Processing

C++ OpenCV Advanced Image Processing

Advanced image processing refers to further implementing more complex tasks on the basis of basic image processing (such as filtering and edge detection), such as image segmentation, contour detection, morphological operations, and histogram processing. These techniques are widely used in target detection, image analysis, medical image processing, and other fields.

Application scenarios of advanced image processing

** Medical image analysis:**

Target detection and tracking:

Image enhancement:


Image segmentation

Image segmentation is an important step in image processing; it divides an image into multiple regions or objects for further analysis and processing. Common image segmentation methods include threshold-based segmentation, edge-based segmentation, and region-based segmentation.

Threshold-based segmentation

Threshold-based segmentation is one of the simplest image segmentation methods. It sets one or more thresholds to classify image pixel values into different categories. Common threshold segmentation methods include global thresholding and adaptive thresholding.

Global thresholding

Global thresholding uses a fixed threshold to divide an image into foreground and background. OpenCV provides cv::threshold function to achieve this.



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

cv::Mat dst;

cv::threshold(src, dst, 128, 255, cv::THRESH_BINARY);

In the code above,128 is the threshold,255 is the maximum pixel value,cv::THRESH_BINARY indicates the use of the binarization method.

Adaptive thresholding

Adaptive thresholding dynamically adjusts the threshold based on local regions of the image. OpenCV provides cv::adaptiveThreshold function to achieve this.



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

cv::Mat dst;

cv::adaptiveThreshold(src, dst, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 11, 2);

In the code above,255 is the maximum pixel value,cv::ADAPTIVE_THRESH_MEAN_C indicates the use of the local mean as the threshold,11 is the neighborhood size,2 is a constant.

Edge-based segmentation

Edge-based segmentation segments an image by detecting edges in the image. Common edge detection algorithms include Canny edge detection and the Sobel operator.

Canny edge detection

Canny edge detection is a multi-stage edge detection algorithm. OpenCV provides cv::Canny function to achieve this.



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

cv::Mat edges;

cv::Canny(src, edges, 100, 200);

In the code above,100 and 200 are the two thresholds of the Canny algorithm.

Region-based segmentation (watershed algorithm)

Region-based segmentation achieves segmentation by dividing an image into multiple regions. The watershed algorithm is a commonly used region-based segmentation method.

Watershed algorithm

The watershed algorithm treats an image as a topographic map and segments it by simulating the flow of water. OpenCV provides cv::watershed function to achieve this.



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

cv::Mat markers = cv::Mat::zeros(src.size(), CV_32S);

cv::watershed(src, markers);

In the code above,markers is the marker matrix used to store the segmentation result.


Contour detection

Contour detection is an important step in image processing; it detects object boundaries in an image. OpenCV provides various functions for contour detection and processing.

Finding contours

Finding contours is the first step in contour detection. OpenCV provides cv::findContours function to achieve this.



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

std::vector> contours;

std::vector hierarchy;

cv::findContours(src, contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);

In the code above,contours is the vector storing the contours,hierarchy is the vector storing the contour hierarchy.

Contour features

Contour features include area, perimeter, bounding box, etc. OpenCV provides various functions to calculate these features.

Area

Area is an important feature of a contour. OpenCV provides cv::contourArea function to calculate the area of a contour.



double area = cv::contourArea(contours[0]);

Perimeter

Perimeter is another important feature of a contour. OpenCV provides cv::arcLength function to calculate the perimeter of a contour.



double perimeter = cv::arcLength(contours[0], true);

Bounding box

The bounding box is the smallest enclosing rectangle of a contour. OpenCV provides cv::boundingRect function to calculate the bounding box.



cv::Rect rect = cv::boundingRect(contours[0]);

Contour drawing

Contour drawing is drawing the detected contours onto the image. OpenCV provides cv::drawContours function to achieve this.



cv::Mat dst = cv::Mat::zeros(src.size(), CV_8UC3);

cv::drawContours(dst, contours, -1, cv::Scalar(0, 255, 0), 2);

In the code above,dst is the image after drawing the contours,cv::Scalar(0, 255, 0) is the color of the contours,2 is the line width of the contours.


Template matching

Template matching is a method for finding a specific template in an image. OpenCV provides cv::matchTemplate function to achieve this.

Single-template matching

Single-template matching finds one template in an image. OpenCV provides cv::matchTemplate function to achieve this.



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

cv::Mat templ = cv::imread("template.jpg");

cv::Mat result;

cv::matchTemplate(src, templ, result, cv::TM_CCOEFF_NORMED);

In the code above,result is the matching result matrix,cv::TM_CCOEFF_NORMED is the matching method.

Multi-template matching

Multi-template matching finds multiple templates in an image. It can be achieved by traversing the matching result matrix.



double minVal, maxVal;

cv::Point minLoc, maxLoc;

cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);

In the code above,maxLoc is the position of the maximum value in the matching result.


Example

Watershed algorithm

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"objects.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 gray

;

    cvtColor

(

image, gray, COLOR_BGR2GRAY

)

;

   

// binarization

    Mat binary

;

    threshold

(

gray, binary,

0

,

255

, THRESH_BINARY_INV

THRESH_OTSU

)

;

   

// remove noise

    Mat kernel

=

getStructuringElement

(

MORPH_RECT, Size

(

3

,

3

)

)

;

    morphologyEx

(

binary, binary, MORPH_OPEN, kernel, Point

(

1

,

1

)

,

2

)

;

   

// compute distance transform

    Mat dist

;

    distanceTransform

(

binary, dist, DIST_L2,

5

)

;

   

// normalize the distance transform image

    normalize

(

dist, dist,

0

,

1.0

, NORM_MINMAX

)

;

   

// binarize the distance transform image

    threshold

(

dist, dist,

0.5

,

1.0

, THRESH_BINARY

)

;

   

// find contours

    Mat dist_8u

;

    dist.

convertTo

(

dist_8u, CV_8U

)

;

    vector

<

vector

<

Point

contours

;

    findContours

(

dist_8u, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE

)

;

   

// create the marker image

    Mat markers

=

Mat

::

zeros

(

dist.

size

(

)

, CV_32S

)

;

   

for

(

size_t

i

=

0

;

i

<

contours.

size

(

)

;

i

++

)

{

        drawContours

(

markers, contours,

static_cast

<

int

(

i

)

, Scalar

(

static_cast

<

int

(

i

)

1

)

,

1

)

;

   

}

   

// apply the watershed algorithm

    watershed

(

image, markers

)

;

   

// Display the result

    Mat result

=

image.

clone

(

)

;

   

for

(

int

i

=

0

;

i

<

markers.

rows

;

i

++

)

{

       

for

(

int

j

=

0

;

j

<

markers.

cols

;

j

++

)

{

           

if

(

markers.

at

<

int

(

i, j

)

==

1

)

{

                result.

at

<

Vec3b

(

i, j

)

=

Vec3b

(

0

,

255

,

0

)

;

// mark boundaries in green

           

}

       

}

   

}

    imshow

(

"Watershed Result"

, result

)

;

    waitKey

(

0

)

;

   

return

0

;

}

Contour detection

Contour detection is used to extract the boundaries of objects in an image.

OpenCV provides the findContours function to detect contours.

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"objects.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 gray

;

    cvtColor

(

image, gray, COLOR_BGR2GRAY

)

;

   

// binarization

    Mat binary

;

    threshold

(

gray, binary,

0

,

255

, THRESH_BINARY_INV

THRESH_OTSU

)

;

   

// find contours

    vector

<

vector

<

Point

contours

;

    vector

<

Vec4i

hierarchy

;

    findContours

(

binary, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE

)

;

   

// draw contours

    Mat result

=

Mat

::

zeros

(

image.

size

(

)

, CV_8UC3

)

;

   

for

(

size_t

i

=

0

;

i

<

contours.

size

(

)

;

i

++

)

{

        drawContours

(

result, contours, i, Scalar

(

0

,

255

,

0

)

,

2

)

;

   

}

   

// Display the result

    imshow

(

"Contours"

, result

)

;

    waitKey

(

0

)

;

   

return

0

;

}

Morphological operations

Morphological operations are shape-based image processing techniques, commonly used to remove noise, separate objects, etc.

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"noisy_image.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 gray

;

    cvtColor

(

image, gray, COLOR_BGR2GRAY

)

;

   

// binarization

    Mat binary

;

    threshold

(

gray, binary,

0

,

255

, THRESH_BINARY_INV

THRESH_OTSU

)

;

   

// define the kernel

    Mat kernel

=

getStructuringElement

(

MORPH_RECT, Size

(

5

,

5

)

)

;

   

// opening operation (remove noise)

    Mat opened

;

    morphologyEx

(

binary, opened, MORPH_OPEN, kernel

)

;

   

// closing operation (fill holes)

    Mat closed

;

    morphologyEx

(

opened, closed, MORPH_CLOSE, kernel

)

;

   

// Display the result

    imshow

(

"Original Binary"

, binary

)

;

    imshow

(

"Opened Image"

, opened

)

;

    imshow

(

"Closed Image"

, closed

)

;

    waitKey

(

0

)

;

   

return

0

;

}

Histogram processing

Histogram processing is used to analyze the pixel distribution of an image; common operations include histogram equalization, histogram matching, etc.

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// Read image

    Mat image

=

imread

(

"low_contrast.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 gray

;

    cvtColor

(

image, gray, COLOR_BGR2GRAY

)

;

   

// histogram equalization

    Mat equalized

;

    equalizeHist

(

gray, equalized

)

;

   

// Display the result

    imshow

(

"Original Image"

, gray

)

;

    imshow

(

"Equalized Image"

, equalized

)

;

    waitKey

(

0

)

;

   

return

0

;

}

Template matching

Template matching is used to find regions in an image that are similar to a template.

Example

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// read the image and template

    Mat image

=

imread

(

"scene.jpg"

)

;

    Mat templ

=

imread

(

"template.jpg"

)

;

   

if

(

image.

empty

(

)

||

templ.

empty

(

)

)

{

       

cout

<<

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

<<

endl

;

       

return

1

;

   

}

   

// template matching

    Mat result

;

    matchTemplate

(

image, templ, result, TM_CCOEFF_NORMED

)

;

   

// find the best matching position

   

double

minVal, maxVal

;

    Point minLoc, maxLoc

;

    minMaxLoc

(

result,

&

minVal,

&

maxVal,

&

minLoc,

&

maxLoc

)

;

   

// draw the rectangle

    rectangle

(

image, maxLoc, Point

(

maxLoc.

x

templ.

cols

, maxLoc.

y

templ.

rows

)

, Scalar

(

0

,

255

,

0

)

,

2

)

;

   

// Display the result

    imshow

(

"Template Matching"

, image

)

;

    waitKey

(

0

)

;

   

return

0

;

}