如何使用Python OpenCV从图像中提取多个对象?

7
我正在尝试使用OpenCV通过颜色从图像中提取对象。 我尝试了反向阈值处理和灰度化,结合cv2.findContours(),但无法递归使用它。此外,我无法弄清楚如何从原始图像中“切出”匹配部分并将其保存到单个文件中。

enter image here

编辑

~
import cv2
import numpy as np

# load the images
empty = cv2.imread("empty.jpg")
full = cv2.imread("test.jpg")

# save color copy for visualization
full_c = full.copy()

# convert to grayscale
empty_g = cv2.cvtColor(empty, cv2.COLOR_BGR2GRAY)
full_g = cv2.cvtColor(full, cv2.COLOR_BGR2GRAY)

empty_g = cv2.GaussianBlur(empty_g, (51, 51), 0)
full_g = cv2.GaussianBlur(full_g, (51, 51), 0)
diff = full_g - empty_g

#  thresholding

diff_th = 
cv2.adaptiveThreshold(full_g,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 
cv2.THRESH_BINARY,11,2)

# combine the difference image and the inverse threshold
zone = cv2.bitwise_and(diff, diff_th, None)

# threshold to get the mask instead of gray pixels
_, zone = cv2.threshold(bag, 100, 255, 0)

# dilate to account for the blurring in the beginning
kernel = np.ones((15, 15), np.uint8)
bag = cv2.dilate(bag, kernel, iterations=1)

# find contours, sort and draw the biggest one
contours, _ = cv2.findContours(bag, cv2.RETR_TREE,
                              cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:3]
i = 0
while i < len(contours):
    x, y, width, height = cv2.boundingRect(contours[i])
    roi = full_c[y:y+height, x:x+width]
    cv2.imwrite("piece"+str(i)+".png", roi)
    i += 1

其中,empty是一张尺寸为1500*1000的白色图像,就像上面那张一样;test也是上面那张图像。

这就是我想到的方法,唯一的缺点是现在出现了第三张图片,而不仅仅是预期的两张,显示了一个阴影区域...


你能详细说明一下你想要实现什么吗? - coffeewin
我正在尝试将每个“蓝色”物品保存在单独的文件中。 - user3491125
1个回答

17

以下是简单的处理步骤:

  1. 获取二值图像。 加载图像,进行灰度变换高斯模糊Otsu二值化,然后进行膨胀操作,得到黑白二值图像。

  2. 提取ROI。 查找轮廓获取边界框,使用Numpy切片提取每个ROI并保存。


二值化图像(Otsu阈值+膨胀)

enter image description here

检测到的ROIs以绿色高亮显示

enter image description here

要提取每个ROI,可以使用cv2.boundingRect()查找边界框坐标,裁剪所需区域,然后保存图像。

x,y,w,h = cv2.boundingRect(c)
ROI = original[y:y+h, x:x+w]

第一个物体

第二个物体

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold, dilate
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))
dilate = cv2.dilate(thresh, kernel, iterations=1)

# Find contours, obtain bounding box coordinates, and extract ROI
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
image_number = 0
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]
    cv2.imwrite("ROI_{}.png".format(image_number), ROI)
    image_number += 1

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

1
更加高效,同时机智的边缘检测看起来比我之前使用的遮罩更可靠,因为它似乎能够剪切掉帧中的其他物体。非常感谢! - user3491125
你如何重新调整感兴趣区域(ROI),使其保持与原始图像相同的比例呢? - user3491125
你所说的“与原始图像相同比例”是什么意思?是指在保持宽高比的同时将提取的 ROIs 缩放到相同的宽度和高度吗? - nathancy
是的,我的意思是将提取的感兴趣区域在白色背景上按照与原始图像相同的大小进行缩放。 - user3491125
这行代码 cnts = cnts[0] if len(cnts) == 2 else cnts[1] 到底是做什么的?当我运行它时,似乎只能找到一个对象,只生成了 "ROI_0"。 - Nikola-Milovic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接