2024-04-20 02:28:13 发布
网友
我有一个矩形的坐标(XMIN,YMIN,XMAX&;YMAX)在一个特定的图像上。我希望以特定角度旋转矩形,然后从图像中裁剪它。 我该怎么做
例如,这个image。我得到了显示在左侧的输出边界框(使用XMIN、YMIN、XMAX和YMAX绘制)。我想根据右边的图像旋转它,然后裁剪它
有人可以提供一个示例代码来获取这个输出,或者给我一个解释链接吗
在Python/OpenCV中有一种方法
输入:
import cv2 import numpy as np from scipy import ndimage # load image img = cv2.imread("berry.png") # convert to hsv hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # threshold using inRange or green range1 = (20,200,170) range2 = (80,255,255) thresh = cv2.inRange(hsv,range1,range2) # get bounding box coordinates from the one outer contour contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = contours[0] if len(contours) == 2 else contours[1] x,y,w,h = cv2.boundingRect(contours[0]) print("bounding_box(x,y,w,h):",x,y,w,h) # rotate image by 10 degree clockwise rotated = img.copy() rotated = ndimage.rotate(img, -10, cval=255) # convert rotated to hsv hsv_rotated = cv2.cvtColor(rotated, cv2.COLOR_BGR2HSV) # threshold using inRange or green range1 = (20,200,170) range2 = (80,255,255) thresh_rotated = cv2.inRange(hsv_rotated,range1,range2) # get bounding box coordinates from the one outer contour contours = cv2.findContours(thresh_rotated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = contours[0] if len(contours) == 2 else contours[1] # draw white filled contour on black background mask = np.zeros_like(thresh_rotated) cv2.drawContours(mask, [contours[0]], -1, (255), -1) # get coordinates of white pixels in mask coords = np.column_stack(np.where(mask.transpose() > 0)) # get rotated rectangle rotrect = cv2.minAreaRect(coords) # rotated rectangle box points box = np.int0(cv2.boxPoints(rotrect)) print("rotate_box_corners:\n",box) # draw rotated rectangle on rotated image result = rotated.copy() cv2.polylines(result, [box], True, (0,0,255), 1) # write result to disk cv2.imwrite("berry_thresh.png", thresh) cv2.imwrite("berry_rotated.png", rotated) cv2.imwrite("berry_thresh_rotated.png", thresh_rotated) cv2.imwrite("berry_mask.png", mask) cv2.imwrite("berry_rotated_box.png", result) # display results cv2.imshow("THRESH", thresh) cv2.imshow("ROTATED", rotated) cv2.imshow("THRESH_ROT", thresh_rotated) cv2.imshow("MASK", mask) cv2.imshow("RESULT", result) cv2.waitKey(0) cv2.destroyAllWindows()
输入中绿线的阈值:
旋转输入:
旋转图像中绿线的阈值:
已填充阈值:
在旋转图像上显示旋转矩形的结果:
输入边界框:
bounding_box(x,y,w,h): 12 13 212 124
输出顶点:
rotate_box_corners: [[222 172] [ 14 136] [ 35 14] [243 51]]
在Python/OpenCV中有一种方法
输入:
输入中绿线的阈值:
旋转输入:
旋转图像中绿线的阈值:
已填充阈值:
在旋转图像上显示旋转矩形的结果:
输入边界框:
输出顶点:
相关问题 更多 >
编程相关推荐