Python OpenCV 截取图片中的小图片
1 import cv2 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 # 读取图像并转换为灰度图像 6 image = cv2.imread('./a.jpg') 7 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 8 9 # 使用 Canny 边缘检测 10 edges = cv2.Canny(gray, 0, 200) # 调整阈值参数 11 12 # 寻找轮廓 13 contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 14 15 # 过滤出长宽大于150的轮廓 16 filtered_contours = [contour for contour in contours if cv2.boundingRect(contour)[2] > 110 and cv2.boundingRect(contour)[3] > 110] 17 18 # 对轮廓按面积进行排序 19 sorted_contours = sorted(filtered_contours, key=cv2.contourArea, reverse=True)[:10] # 只保留最大的五个轮廓 20 21 # 绘制矩形轮廓 22 for contour in sorted_contours: 23 x, y, w, h = cv2.boundingRect(contour) 24 cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) 25 26 # 将轮廓内的区域更改为背景颜色 27 i = 1 28 for contour in sorted_contours: 29 x, y, w, h = cv2.boundingRect(contour) 30 cropped_image = image[y:y+h, x:x+w] 31 # 保存裁剪后的图片 32 cv2.imwrite(str(i)+'.jpg', cropped_image) 33 i+=1 34 35 # 显示结果 36 plt.imshow(image[:,:,::-1])