python - 删除轮廓 OpenCV
问题描述
我的形象
我想得到
我只能得到
我能够找到最大轮廓
def img_counter_max(image_file: str):
img = cv2.imread(image_file)
# grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # меняем цветовую модель с BGR на HSV
cv2.waitKey(0)
# binarize
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
cv2.waitKey(0)
# find contours
ctrs, hier = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# sort contours
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
# sorted_ctrs sorted(ctrs, key=cv2.contourArea, reverse=True)[0]
contour_sizes = [(cv2.contourArea(contour), contour) for contour in sorted_ctrs]
biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]
x, y, w, h = cv2.boundingRect(biggest_contour)
roi = img[y:y + h, x:x + w]
cv2.imwrite("C:\\Users\\dennn\\PycharmProjects\\untitled2\\imag\\roi1.jpg",
roi)
cv2.rectangle(img, (x, y), (x + w, y + h), (90, 255, 0), 2)
from tensorflow.python import Size
resize_img = cv2.resize(img, (512,512))
# cv2.resize(img, Size(512,512), interpolation=cv2.INTER_AREA)
cv2.namedWindow("Display frame", cv2.WINDOW_AUTOSIZE);
cv2.imshow('Display frame', resize_img)
cv2.waitKey(0)
如何获得我需要的图像?
解决方案
我发现排序依据contourArea()
给出了错误的结果。可能它会计算轮廓内的所有点,但不计算它使用的矩形区域 - 这个矩形可以更大。
我boundingRect()
用来获取轮廓使用的矩形,然后使用计算大小w*h
,然后以正确的方式对轮廓进行排序。
我使用for
-loop 来显示具有不同矩形的图像,并查看哪个轮廓给出了预期的区域。通过这种方式,我看到第三个轮廓给出了预期的区域,因此我可以使用[2]
它来获取并保存它。
最终我会使用大小来选择w*h
在某个范围内的区域
expecte_region_size - range < w*h < expecte_region_size + range
最终我会使用for
-loop 来显示具有不同矩形的图像来手动选择要使用哪个矩形保存在文件中。
import cv2
img = cv2.imread('image.jpg')
# grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # меняем цветовую модель с BGR на HSV
# binarize
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# find contours
ctrs, hier = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# find rect and area - and create items [contour, rect, area] - but sorting by area gives wrong results
#items = [[ctr, cv2.boundingRect(ctr), cv2.contourArea(ctr)] for ctr in ctrs]
# find rect - and create items [contour, rect]
items = [[ctr, cv2.boundingRect(ctr)] for ctr in ctrs]
# find rect's size and create items [contour, rect, size]
items = [[ctr, rect, rect[2]*rect[3]] for ctr, rect in items]
# sort by size
items = sorted(items, key=lambda x: x[2], reverse=True)
for index, item in enumerate(items[:5]):
contour = item[0]
x, y, w, h = item[1]
size = item[2]
print(index, '->', size, '(', x, y, w, h, ')')
img_copy = img.copy()
cv2.rectangle(img_copy, (x, y), (x + w, y + h), (0, 0, 255), 15)
resize_img = cv2.resize(img_copy, (512,512))
cv2.imshow('frame', resize_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# --- save image ---
item = items[2]
contour = item[0]
x, y, w, h = item[1]
size = item[2]
img = img[y:y+h, x:x+w]
cv2.imwrite('output.jpg', img)
预习:
输出:
推荐阅读
- mysql - 带有 WINDOWS10 的 MySQLdump:OS errno 13 - 执行“SELECT INTO OUTFILE”时(权限被拒绝)
- python - 如何将未连接的networkx图分成多个相互不相交的连接图?
- http - Golang 的 (*http.ResponseWriter) Write() 方法是否会阻塞,直到客户端收到数据?
- pandoc - MathJax 括号 - \right 的分隔符缺失或无法识别
- halide - 通过 Cygwin 在 Windows 环境中使用 Linux 命令编译 Halide 程序时出错
- javascript - 图表 JS 使用 addData 在 x 轴上添加标签
- java - 使用 Java 加入 Firebase 实时数据库?
- amazon-web-services - AWS放大graphql突变:不能为不可为空的字段返回null
- botframework - BotService Slack 通道连接向发送的消息返回 Slack API 错误
- python - 如何访问 aTag href 后的标签以获取网站上列出的产品名称?