其他方法仅在旋转后矩形的内容在旋转后的图像中有效,否则在其他情况下将严重失败 。如果某些部分丢失了怎么办?请参阅以下示例:
如果要使用上述方法裁剪旋转的矩形文本区域,
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))
现在裁剪的图像变为
好多了,不是吗?如果仔细检查,您会发现裁切后的图像中存在一些黑色区域。这是因为检测到的矩形的一小部分超出了图像的范围。为了解决这个问题,您可以稍稍填充图像 ,然后裁剪。 这个答案有一个例子。
现在,我们比较两种方法从图像中裁剪旋转的矩形。此方法不需要旋转图像,并且可以用更少的代码更好地处理此问题。
0
下图将告诉您我想要什么。
我有图像中矩形的信息(宽度,高度,中心点和旋转度)。现在,我想编写一个脚本将其剪切并保存为图像,但也将其拉直。如图所示,我想从图像内部显示的矩形转到外部显示的矩形。
我正在使用OpenCV Python。 请告诉我一种实现此目标的方法。
请显示一些代码,因为很难找到OpenCV Python的示例。