如何基于OpenCV的cv.boundingRect裁剪并导出图像中的六个矩形
解决OpenCV循环导出裁剪矩形图像的问题
你的代码已经成功获取了每个轮廓的 bounding box,只需要添加图像裁剪与保存的逻辑即可。以下是修复后的完整代码及关键说明:
修复后的代码
import cv2 as cv import numpy as np import random as rng # 保留原始彩色图像(如果需要导出彩色裁剪结果) img_color = cv.imread('newsample.jpg') # 用于处理的灰度图像 img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(img_gray, 110, 255, cv.THRESH_BINARY_INV) median = cv.medianBlur(thresh, 13) # 提取外部轮廓 contours, hierarchy = cv.findContours(median, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) contours_poly = [None]*len(contours) boundRect = [None]*len(contours) for i, c in enumerate(contours): contours_poly[i] = cv.approxPolyDP(c, 3, True) boundRect[i] = cv.boundingRect(contours_poly[i]) drawing = np.zeros((img_gray.shape[0], img_gray.shape[1], 3), dtype=np.uint8) for i in range(len(contours)): # 提取当前矩形的坐标与尺寸 x, y, w, h = boundRect[i] # 过滤过小的轮廓(避免保存噪声,可根据实际情况调整阈值) if w * h < 1000: continue # 裁剪图像:OpenCV图像的索引是 [y起始:y结束, x起始:x结束] cropped_img = img_color[y:y+h, x:x+w] # 保存裁剪后的图像 cv.imwrite(f'cropped_rect_{i}.jpg', cropped_img) # 绘制轮廓与矩形(原逻辑保留) color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256)) cv.drawContours(drawing, contours_poly, i, color) cv.rectangle(drawing, (int(x), int(y)), (int(x+w), int(y+h)), color, 2) cv.imshow('Contours', drawing) cv.waitKey(0) cv.destroyAllWindows()
关键修复点
- 保留原始彩色图像:原代码将读取的图像直接转为灰度,导致无法导出彩色裁剪结果,现在分开存储彩色与灰度图像。
- 正确的图像裁剪逻辑:OpenCV的图像数组是
[高度(y轴), 宽度(x轴)]的顺序,所以裁剪时要使用img[y:y+h, x:x+w],不要搞反x和y的顺序。 - 过滤无效轮廓:添加面积阈值过滤,避免将图像中的小噪声轮廓也保存为裁剪图,可根据你的图像实际大小调整
1000这个阈值。 - 循环保存图像:使用
cv.imwrite()结合格式化字符串,为每个裁剪图生成唯一的文件名(如cropped_rect_0.jpg、cropped_rect_1.jpg等)。
如果需要导出灰度裁剪结果,只需将cropped_img = img_color[y:y+h, x:x+w]替换为cropped_img = img_gray[y:y+h, x:x+w]即可。
内容的提问来源于stack exchange,提问作者Annisa Septyana Ningrum
相关产品推荐
相关产品推荐

