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

OpenCV Image Stitching

OpenCV Image Stitching

Image stitching is an important application in computer vision that can combine multiple images with overlapping regions into a single larger image.

Common application scenarios include panorama generation, satellite image stitching, and so on.

OpenCV is a powerful computer vision library that provides rich tools to implement image stitching.

This article will introduce in detail how to use OpenCV for image stitching, focusing on techniques for feature point detection and matching.

Application scenarios

Basic flow of image stitching

The basic flow of image stitching can be divided into the following steps:

  1. Image reading: read the images to be stitched.
  2. Feature Point Detection: detect keypoints (feature points) in each image.
  3. Feature point matching: match these feature points between different images.
  4. Compute the transformation matrix: compute the transformation matrix between images based on the matched feature points.
  5. Image blending: stitch the images according to the transformation matrix and perform blending to eliminate stitching traces.

Next, we will explain the implementation of each step in detail.


1. Image reading

First, we need to read the images to be stitched. OpenCV provides cv2.imread() function to read the image.

Example

import

cv2

Read an image

image1

=

cv2.

imread

(

'image1.jpg'

)

image2

=

cv2.

imread

(

'image2.jpg'

)

Check whether the image was read successfully

if

image1

is

None

or

image2

is

None

:

   

print

(

"Error: Unable to read image"

)

    exit

(

)


2. Feature point detection

Feature point detection is a key step in image stitching. OpenCV provides a variety of feature point detection algorithms, such as SIFT, SURF, ORB, and so on. Here we use SIFT as an example for explanation.

Example

Create a SIFT detector

sift

=

cv2.

SIFT_create

(

)

Detect feature points and descriptors

keypoints1

,

descriptors1

=

sift.

detectAndCompute

(

image1

,

None

)

keypoints2

,

descriptors2

=

sift.

detectAndCompute

(

image2

,

None

)

detectAndCompute() The function returns two values: keypoints and descriptors. Keypoints are salient points in the image, and descriptors are descriptions of these keypoints used for subsequent matching.


3. Feature point matching

After detecting feature points, we need to match these feature points between different images. OpenCV provides BFMatcher or FlannBasedMatcher to perform feature point matching.

Example

Create a BFMatcher object

bf

=

cv2.

BFMatcher

(

)

Use KNN matching

matches

=

bf.

knnMatch

(

descriptors1

,

descriptors2

,

k

=

2

)

Apply the ratio test to filter out good matches

good_matches

=

[

]

for

m

,

n

in

matches:

   

if

m.

distance

<

0.75

distance

:

        good_matches.

append

(

m

)

knnMatch() The function returns the two best matches for each feature point. We use the ratio test (Lowe's ratio test) to filter out good matching points.


4. Compute the transformation matrix

After obtaining good matching points, we can use these points to compute the transformation matrix between images. A commonly used transformation matrix is the homography matrix (Homography), which can map points in one image to another image.

Example

Extract the coordinates of matching points

src_pts

=

np.

float32

(

[

keypoints1

[

m.

queryIdx

]

.

pt

for

m

in

good_matches

]

)

.

reshape

(

1

,

1

,

2

)

dst_pts

=

np.

float32

(

[

keypoints2

[

m.

trainIdx

]

.

pt

for

m

in

good_matches

]

)

.

reshape

(

1

,

1

,

2

)

Compute the homography matrix

H

,

_

=

cv2.

findHomography

(

src_pts

,

dst_pts

,

cv2.

RANSAC

,

5.0

)

findHomography() The function returns a 3x3 homography matrix H, which can map image1 points in one image to another image. image2 it.


5. Image blending

Finally, we use the computed homography matrix to stitch the images and perform blending to eliminate stitching traces.

Example

Get image dimensions

h1

,

w1

=

image1.

shape

[

:

2

]

h2

,

w2

=

image2.

shape

[

:

2

]

Compute the dimensions of the stitched image

pts

=

np.

float32

(

[

[

0

,

0

]

,

[

0

,

h1

]

,

[

w1

,

h1

]

,

[

w1

,

0

]

]

)

.

reshape

(

1

,

1

,

2

)

dst

=

cv2.

perspectiveTransform

(

pts

,

H

)

[

x_min

,

y_min

]

=

np.

int32

(

dst.

min

(

axis

=

0

)

.

ravel

(

)

0.5

)

[

x_max

,

y_max

]

=

np.

int32

(

dst.

max

(

axis

=

0

)

.

ravel

(

)

0.5

)

Compute the translation matrix

translation_matrix

=

np.

array

(

[

[

1

,

0

,

-x_min

]

,

[

0

,

1

,

-y_min

]

,

[

0

,

0

,

1

]

]

)

Apply the translation matrix for image stitching

result

=

cv2.

warpPerspective

(

image1

,

translation_matrix.

dot

(

H

)

,

(

x_max - x_min

,

y_max - y_min

)

)

result

[

-y_min:h2 - y_min

,

-x_min:w2 - x_min

]

=

image2

Display the stitching result

cv2.

imshow

(

'Result'

,

result

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)

warpPerspective() The function performs a perspective transform based on the homography matrix H locks image1 and stitches it with image2 to complete the stitching.


Application implementation

The following is the complete code for image stitching using feature point detection and matching:

Example

import

cv2

import

numpy

as

np

1. Load images

image1

=

cv2.

imread

(

"path/to/image1.jpg"

)

image2

=

cv2.

imread

(

"path/to/image2.jpg"

)

2. Convert to grayscale

gray1

=

cv2.

cvtColor

(

image1

,

cv2.

COLOR_BGR2GRAY

)

gray2

=

cv2.

cvtColor

(

image2

,

cv2.

COLOR_BGR2GRAY

)

3. Feature point detection

sift

=

cv2.

SIFT_create

(

)

keypoints1

,

descriptors1

=

sift.

detectAndCompute

(

gray1

,

None

)

keypoints2

,

descriptors2

=

sift.

detectAndCompute

(

gray2

,

None

)

4. Feature point matching

matcher

=

cv2.

BFMatcher

(

)

matches

=

matcher.

knnMatch

(

descriptors1

,

descriptors2

,

k

=

2

)

5. Filter matching points

good_matches

=

[

]

for

m

,

n

in

matches:

   

if

m.

distance

<

0.75

distance

:

        good_matches.

append

(

m

)

6. Compute the homography matrix

if

len

(

good_matches

)

10

:

    src_pts

=

np.

float32

(

[

keypoints1

[

m.

queryIdx

]

.

pt

for

m

in

good_matches

]

)

.

reshape

(

1

,

1

,

2

)

    dst_pts

=

np.

float32

(

[

keypoints2

[

m.

trainIdx

]

.

pt

for

m

in

good_matches

]

)

.

reshape

(

1

,

1

,

2

)

    H

,

_

=

cv2.

findHomography

(

src_pts

,

dst_pts

,

cv2.

RANSAC

,

5.0

)

else

:

   

print

(

"Not enough matches found."

)

    exit

(

)

7. Image transformation

height1

,

width1

=

image1.

shape

[

:

2

]

height2

,

width2

=

image2.

shape

[

:

2

]

warped_image

=

cv2.

warpPerspective

(

image1

,

H

,

(

width1 + width2

,

height1

)

)

8. Image stitching

warped_image

[

0

:height2

,

0

:width2

]

=

image2

9. Display the result

cv2.

imshow

(

"Stitched Image"

,

warped_image

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)