Hello, Habr! We continue the tutorial on the opencv library in python. For those who have not read the first part, here: Part 1 , and everyone else - fun reading!
Introduction
Now that you are familiar with the basics of this library, it's time to start basic transformations of images: resizing, offset along the axes, cropping (cropping), rotating.
Image resizing
, — . opencv resize():
def resizing():
res_img = cv2.resize(img, (500, 900), cv2.INTER_NEAREST)
, , — , , — (). — , . , , . , (cv2.INTER_NEAREST) , — . opencv : cv2.INTER_AREA, cv2.INTER_LINEAR( ), cv2.INTER_CUBIC cv2.INTER_LANCZOS4. cv2.INTER_AREA, — cv2.INTER_LINEAR. , , / , 1.5 , — . . :
res_img_nearest = cv2.resize(img, (int(w / 1.4), int(h / 1.4)),
cv2.INTER_NEAREST)
res_img_linear = cv2.resize(img, (int(w / 1.4), int(h / 1.4)),
cv2.INTER_LINEAR)
— , — :
. — . , :
:
def resizing(new_width=None, new_height=None, interp=cv2.INTER_LINEAR):
h, w = img.shape[:2]
if new_width is None and new_height is None:
return img
if new_width is None:
ratio = new_height / h
dimension = (int(w * ratio), new_height)
else:
ratio = new_width / w
dimension = (new_width, int(h * ratio))
res_img = cv2.resize(img, dimension, interpolation=interp)
ratio. , None, / /. , dimension cv2.resize().
cv2.warpAffine() , , :
def shifting():
h, w = img.shape[:2]
translation_matrix = np.float32([[1, 0, 200], [0, 1, 300]])
dst = cv2.warpAffine(img, translation_matrix, (w, h))
cv2.imshow(', ', dst)
cv2.waitKey(0)
, translation_matrix :
— [1, 0, tx ], tx — , . tx , — .
— [ 0, 1, ty], ty — , . ty , — . , .
, , , cv2.warpAffine(), , — , — . , :
, , :
def cropping():
crop_img = img[10:450, 300:750]
numpy , (300, 10) (750, 450), 10 — y, 300 — x, 450 — y 750 — x. , , :
, , — :
def rotation():
(h, w) = img.shape[:2]
center = (int(w / 2), int(h / 2))
rotation_matrix = cv2.getRotationMatrix2D(center, -45, 0.6)
rotated = cv2.warpAffine(img, rotation_matrix, (w, h))
, , , cv2.getRotationMatrix2D(). , opencv , . , , — . 0.6, 40%, , . numpy, cv2.warpAffine(). , :
Now the second part has come to an end, the source code is available on github . Thank you for your attention! See you soon!