如何单独保存被框包围的图像



我是python新手。我想单独保存通过轮廓提取的图像。提前谢谢。

region = []等高线,层次= cv2。findContours (dilation2 cv2。RETR_TREE cv2.CHAIN_APPROX_SIMPLE)对于range(len(contours))中的I:CNT = contours[i]

# Calculate contour area and screen out small areas
area = cv2.contourArea(cnt)
if (area < 80):
continue
# Find the smallest rectangle
rect = cv2.minAreaRect(cnt)
print ("rect is: ")
print (rect)
# box is the coordinate of four points
box = cv2.boxPoints(rect)
box = np.int0(box)
# Computing height and width
height = abs(box[0][1] - box[2][1])
width = abs(box[0][0] - box[2][0])
# According to the characteristics of the text, select those too thin rectangles, leaving flat ones.
if (height > width * 3):
continue
region.append(box)
# Draw outline
for box in region:
cv2.drawContours(img, [box], 0, (0, 255, 0), 1)
cv2.imshow('img', img)

您已经有了每个轮廓的框坐标。现在你所要做的就是裁剪这些框并将它们存储为图像。

将框坐标存储为:box = [x, y, w, h]式中,(x, y)为箱体左上角坐标,w为箱体宽度,h为箱体高度。

现在裁剪这个框的图像并保存,使用下面的代码:

box_image = image[y : y+h, x: x+w]
cv2.imwrite("image_name.jpg", box_image)

最新更新