python opencv旋转_如何在python中使用opencv来拉直图像的旋转矩形区域?

The other methods will work only if the content of the rectangle is in the rotated image after rotation and will fail badly in other situations . 如果部分丢失会怎么样?请参阅以下示例:

如果要使用上述方法裁剪旋转的矩形文本区域,

import cv2

import numpy as np

def main():

img = cv2.imread("big_vertical_text.jpg")

cnt = np.array([

[[64, 49]],

[[122, 11]],

[[391, 326]],

[[308, 373]]

])

print("shape of cnt: {}".format(cnt.shape))

rect = cv2.minAreaRect(cnt)

print("rect: {}".format(rect))

box = cv2.boxPoints(rect)

box = np.int0(box)

print("bounding box: {}".format(box))

cv2.drawContours(img, [box], 0, (0, 0, 255), 2)

img_crop, img_rot = crop_rect(img, rect)

print("size of original img: {}".format(img.shape))

print("size of rotated img: {}".format(img_rot.shape))

print("size of cropped img: {}".format(img_crop.shape))

new_size = (int(img_rot.shape[1]/2), int(img_rot.shape[0]/2))

img_rot_resized = cv2.resize(img_rot, new_size)

new_size = (int(img.shape[1]/2)), int(img.shape[0]/2)

img_resized = cv2.resize(img, new_size)

cv2.imshow("original contour", img_resized)

cv2.imshow("rotated image", img_rot_resized)

cv2.imshow("cropped_box", img_crop)

# cv2.imwrite("crop_img1.jpg", img_crop)

cv2.waitKey(0)

def crop_rect(img, rect):

# get the parameter of the small rectangle

center = rect[0]

size = rect[1]

angle = rect[2]

center, size = tuple(map(int, center)), tuple(map(int, size))

# get row and col num in img

height, width = img.shape[0], img.shape[1]

print("width: {}, height: {}".format(width, height))

M = cv2.getRotationMatrix2D(center, angle, 1)

img_rot = cv2.warpAffine(img, M, (width, height))

img_crop = cv2.getRectSubPix(img_rot, size, center)

return img_crop, img_rot

if __name__ == "__main__":

main()

这就是你将得到的:

显然,有些部件被切掉了!为什么不直接扭曲旋转的矩形,因为我们可以用 cv.boxPoints() 方法得到它的四个角点?

import cv2

import numpy as np

def main():

img = cv2.imread("big_vertical_text.jpg")

cnt = np.array([

[[64, 49]],

[[122, 11]],

[[391, 326]],

[[308, 373]]

])

print("shape of cnt: {}".format(cnt.shape))

rect = cv2.minAreaRect(cnt)

print("rect: {}".format(rect))

box = cv2.boxPoints(rect)

box = np.int0(box)

width = int(rect[1][0])

height = int(rect[1][1])

src_pts = box.astype("float32")

dst_pts = np.array([[0, height-1],

[0, 0],

[width-1, 0],

[width-1, height-1]], dtype="float32")

M = cv2.getPerspectiveTransform(src_pts, dst_pts)

warped = cv2.warpPerspective(img, M, (width, height))

现在裁剪的图像变成了

好多了,不是吗?如果仔细检查,您会注意到裁剪图像中有一些黑色区域 . 这是因为检测到的矩形的一小部分超出了图像的范围 . 为了解决这个问题,你可以稍微做一点,然后做一些裁剪 . this answer中有一个例子 .

现在,我们比较两种方法从图像中裁剪旋转的矩形 . 此方法不需要旋转图像,并且可以使用更少的代码更优雅地处理此问题 .

你可能感兴趣的:(python,opencv旋转)