【发布时间】:2019-09-11 09:22:57
【问题描述】:
我想在图像中裁剪出一个充满小曲线的区域。
使用 opening 变形,我可以消除大部分噪音。结果是这样的:
我尝试使用 dilate 将这些像素连接到我想要的区域,但结果并不理想。
opencv中有没有可以定位这个区域的函数?
【问题讨论】:
-
您对结果图像的期望是什么?
标签: python image opencv image-processing computer-vision
我想在图像中裁剪出一个充满小曲线的区域。
使用 opening 变形,我可以消除大部分噪音。结果是这样的:
我尝试使用 dilate 将这些像素连接到我想要的区域,但结果并不理想。
opencv中有没有可以定位这个区域的函数?
【问题讨论】:
标签: python image opencv image-processing computer-vision
你在正确的轨道上,这是一种使用形态变换的方法
这个想法是将所需区域连接到单个轮廓中,然后使用最大面积进行过滤。这样,我们可以将区域作为一个整体来抓取。这是检测到的区域
之后,我们可以用 Numpy 切片提取区域
import cv2
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (9,9), 0)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
dilate = cv2.dilate(opening, dilate_kernel, iterations=5)
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original[y:y+h, x:x+w]
break
cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('dilate', dilate)
cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.waitKey(0)
【讨论】:
这是我使用 NumPy 的 sum 的方法。只需将沿 x 和 y 轴的像素值分别求和,为描述所需区域的最小像素数设置一些阈值,并获得适当的列和行索引。
让我们看看下面的代码:
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Read input image; get shape
img = cv2.imread('images/UKf5Z.jpg', cv2.IMREAD_GRAYSCALE)
w, h = img.shape[0:2]
# Threshold to prevent JPG artifacts
_, img = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
# Sum pixels along x and y axis
xSum = np.sum(img / 255, axis=0)
ySum = np.sum(img / 255, axis=1)
# Visualize curves
plt.plot(xSum)
plt.plot(ySum)
plt.show()
# Set up thresholds
xThr = 15
yThr = 15
# Find proper row indices
tmp = np.argwhere(xSum > xThr)
tmp = tmp[np.where((tmp > 20) & (tmp < w - 20))]
x1 = tmp[0]
x2 = tmp[-1]
# Find proper column indices
tmp = np.argwhere(ySum > yThr)
tmp = tmp[np.where((tmp > 20) & (tmp < h - 20))]
y1 = tmp[0]
y2 = tmp[-1]
# Visualize result
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.rectangle(out, (x1, y1), (x2, y2), (0, 0, 255), 4)
cv2.imshow('out', out)
cv2.waitKey(0)
求和曲线如下所示(仅用于可视化目的):
而且,为了可视化,我只画了一个由找到的索引描述的红色矩形。
如您所见,我手动排除了一些 20 像素的“边框”区域,因为存在一些较大的伪影。根据您所需区域的位置,这可能就足够了。否则,应保留您使用形态学开放的方法。
希望有帮助!
编辑: 正如 Mark in his answer 所建议的那样,使用 mean 而不是 sum 可以避免对不同图像尺寸的适应。适当地更改代码留给读者。 :-)
【讨论】: