Article directory
Preface
- When making paper illustrations, it is sometimes required to enlarge parts of the picture to show details, and at the same time splice the enlarged picture onto the original picture to facilitate observation and comparison.
- Of course, it can also be easily implemented by directly using the drawing software or other software that comes with the computer. However, if you encounter multiple algorithms to process one picture and then compare multiple pictures, it will be inconvenient. Here I will mainly post the python code. accomplish.
cv2.rectangle() function
cv2.rectangle(img, pt1, pt2, color, thickness )
The function is to draw a rectangular frame on the picture and has no return value.
Parameter list:
img: picture
pt1: coordinates of the upper left corner of the rectangular box
pt2: coordinates of the lower right corner of the rectangular box
color: font color
thickness: font thickness
Example
import cv2
image = cv2.imread('F://test.png')
pt1 = (10, 190) # 长方形框左上角坐标
pt2 = (160, 270) # 长方形框右下角坐标
cv2.rectangle(image, pt1, pt2, (255, 0, 0), 5)
cv2.imshow('demo', image)
cv2.resize() function
cv2.resize(src, dsize)
The function is to scale the image to the specified size, and the return value is the changed image.
Parameter list:
src: input image
dsize: output image size
Example
import cv2
image = cv2.imread('F://test.png')
h, w = image.shape[0:2]
print(f'原来图片的大小:{w}×{h}')
image = cv2.resize(image, (150, 300))
h, w = image.shape[0:2]
print(f'缩小后图片的大小:{w}×{h}')
np.hstack() and np.vstack() functions
np.hstack((img1, img2, ···))
and np.vstack((img1, img2·, ···))
. np.hstack()
and np.vstack()
are two matrix splicing functions provided by numpy. As the name suggests, they np.hstack()
are splicing in the horizontal direction and np.vstack()
splicing in the vertical direction.
Parameter list :
img1: the first image
img2: the second image
imgn: the nth image
Requirements : the number of rows or columns of the input images is the same
Example
import cv2
import numpy as np
image1 = cv2.imread('F://test.png')
image2 = cv2.resize(image1, (150, 300))
image3 = cv2.resize(image1, (550, 410))
image = np.hstack((image1, image2))
image = np.vstack((image, image3))
cv2.imshow('demo', image)
Realize local frame magnification and splicing
import cv2
import numpy as np
image = cv2.imread('F://test.png')
# 第一个局部放大图
pt1 = (150, 70) # 长方形框左上角坐标
pt2 = (250, 130) # 长方形框右下角坐标
cv2.rectangle(image, pt1, pt2, (0, 0, 255), 2)
patch1 = image[70:130, 150:250, :]
patch1 = cv2.resize(patch1, (200, 120))
# 第二个局部放大图
pt1 = (265, 70) # 长方形框左上角坐标
pt2 = (365, 130) # 长方形框右下角坐标
cv2.rectangle(image, pt1, pt2, (0, 255, 0), 2)
patch2 = image[70:130, 265:365, :]
patch2 = cv2.resize(patch2, (200, 120))
# 拼接
patch = np.hstack((patch1, patch2))
image = np.vstack((image, patch))
cv2.imshow('demo', image)
cv2.imwrite('F://test_result.png', image)