【发布时间】:2017-07-12 09:17:50
【问题描述】:
【问题讨论】:
-
我很确定边缘检测和循环遍历边缘和图像内的像素并在新图像中设置这些像素!
标签: opencv image-processing blur background-subtraction
【问题讨论】:
标签: opencv image-processing blur background-subtraction
这个问题已经有一段时间了,我是从另一个问题那里得到的指示。我想我会用一些代码来回答,只是为了把一些实现放在前面答案的想法后面。
从 Canny 边缘检测开始寻找前景:
放大图像以连接精巧的线条。使用 findContours 并选择最大的一个来创建蒙版。
遮罩上有孔,因为轮廓碰到图像的边缘。我们可以通过反转遮罩并再次使用 findContours 来填充小孔。这次我们将过滤掉非常大的轮廓,并将剩余的轮廓绘制到蒙版上。
现在我们只需要使用蒙版来裁剪我们的图像。
这是代码
import cv2
import numpy as np
# load image
img = cv2.imread("foreground.jpg");
# grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
# canny
canned = cv2.Canny(gray, 100, 200);
# dilate to close holes in lines
kernel = np.ones((5,5),np.uint8)
mask = cv2.dilate(canned, kernel, iterations = 1);
# find contours
# Opencv 3.4, if using a different major version (4.0 or 2.0), remove the first underscore
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);
# find big contours
biggest_cntr = None;
biggest_area = 0;
for contour in contours:
area = cv2.contourArea(contour);
if area > biggest_area:
biggest_area = area;
biggest_cntr = contour;
# draw contours
crop_mask = np.zeros_like(mask);
cv2.drawContours(crop_mask, [biggest_cntr], -1, (255), -1);
# fill in holes
# inverted
inverted = cv2.bitwise_not(crop_mask);
# contours again
_, contours, _ = cv2.findContours(inverted, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);
# find small contours
small_cntrs = [];
for contour in contours:
area = cv2.contourArea(contour);
if area < 20000:
print(area);
small_cntrs.append(contour);
# draw on mask
cv2.drawContours(crop_mask, small_cntrs, -1, (255), -1);
# opening + median blur to smooth jaggies
crop_mask = cv2.erode(crop_mask, kernel, iterations = 1);
crop_mask = cv2.dilate(crop_mask, kernel, iterations = 1);
crop_mask = cv2.medianBlur(crop_mask, 5);
# crop image
crop = np.zeros_like(img);
crop[crop_mask == 255] = img[crop_mask == 255];
# show
cv2.imshow("original", img);
cv2.imshow("gray", gray);
cv2.imshow("canny", canned);
cv2.imshow("mask", crop_mask);
cv2.imshow("cropped", crop);
cv2.waitKey(0);
【讨论】: