【问题标题】:Cropping rectangular extensions from ROI in OpenCV [closed]在 OpenCV 中从 ROI 裁剪矩形扩展 [关闭]
【发布时间】:2019-12-31 11:21:32
【问题描述】:

我有这张图片:

我想从整个 ROI 中提取下面突出显示的矩形扩展。

【问题讨论】:

  • This 将是一个答案。
  • 不,这对我不起作用,因为矩形是整个对象的一部分并且不位于边缘,因此边缘检测不会区分想要的矩形与对象。
  • 欢迎来到stackoverflow。这不是免费的代码编写服务。它也不是教程或网络搜索的替代品。请阅读How to Ask。然后edit您的问题并添加您迄今为止尝试过的代码。当你运行它时会发生什么?你期望会发生什么?有什么错误吗?

标签: python opencv image-processing shapes extraction


【解决方案1】:

这是使用morphological operations + 轮廓过滤和cv2.contourArea() 的简单方法


大津的阈值->形态闭合+反转->结果

代码

import cv2

# Load image, convert to grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Create kernel and morph close 
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
close = 255 - cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=5)

# Find contours and filter using contour area
cnts = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 100 and area < 25000:
        cv2.drawContours(image, [c], -1, (36,255,12), 4)

cv2.imshow('thresh', thresh)
cv2.imshow('close', close)
cv2.imshow('image', image)
cv2.waitKey()

【讨论】:

    猜你喜欢
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多