import cv2 import numpy as np img_list = [] image = cv2.imdecode(np.fromfile("E:/DIRPIC/pic/camera/111.png", dtype=np.uint8), -1) if len(image.shape) == 3: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: gray = image _, binary = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) drawing = np.zeros_like(binary) cv2.drawContours(drawing, contours, -1, 255, 2) # 最后两个参数分别为颜色和线宽 contours2 = sorted(contours, key=lambda i: len(i), reverse=True) contour_total = [] for cnt in contours2: contour_total.extend(cnt) if cnt.shape[0] >= 1500 else None x_top, y_top, w, h = cv2.boundingRect(np.array(contour_total)) img_crop = image[y_top:y_top + h, x_top:x_top + w].copy() img_list.append(cv2.resize(img_crop, (256, 256))) cv2.destroyAllWindows()
从图像中提取并裁剪出符合指定条件的轮廓区域,并将裁剪后的图像添加到
img_list
列表中。首先,代码使用
cv2.imdecode()
函数读取图像文件,并根据文件路径创建一个图像对象image
。然后,通过判断
image
的维度数来确定是否需要将图像转换为灰度图像。如果图像是彩色图像(维度数为3),则使用cv2.cvtColor()
函数将图像转换为灰度图像;否则,将image
赋值给灰度图像变量gray
。接下来,使用
cv2.threshold()
函数对灰度图像gray
进行阈值处理,将图像转换为二值图像binary
。然后,使用
cv2.findContours()
函数找到二值图像中的轮廓。返回的轮廓列表存储在contours
变量中。接下来,创建一个与二值图像大小相同的空白图像
drawing
,并使用cv2.drawContours()
函数将轮廓绘制在drawing
上。然后,对轮廓列表
contours
进行排序,按照轮廓长度降序排列,存储在contours2
变量中。接下来,通过遍历
contours2
中的轮廓,将点数大于等于 1500 的轮廓的点集合并到contour_total
中。然后,使用
cv2.boundingRect()
函数计算contour_total
的边界框位置信息,并将结果存储在变量x_top
、y_top
、w
和h
中。最后,根据边界框位置信息,使用切片操作从原始图像
image
中提取出裁剪后的图像区域,并使用cv2.resize()
函数将裁剪后的图像调整为大小为 (256, 256) 的图像,并将其添加到img_list
列表中。