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

标签 python image opencv image-processing computer-vision

我正在尝试使用 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 为上图。

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

最佳答案

这里有一个简单的方法:

  1. 获取二进制图像。 Load the image , grayscale , Gaussian blur , Otsu's threshold , 然后 dilate获得二进制黑白图像。

  2. 提取投资返回率。 Find contours , obtain bounding boxes ,使用Numpy切片提取ROI,并保存每个ROI


二值图像(大津阈值+膨胀)

enter image description here

检测到的 ROI 以绿色突出显示

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()

关于python - 如何使用 Python OpenCV 从图像中提取多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56604151/

相关文章:

python - 获取完整的回溯

python - 将 Beautiful Soup 表抓取结果导出到 CSV

java - 如何缩放从 PNG 加载的透明 org.eclipse.swt.graphics.Image; java

c++ - 对 RGB 图像执行阈值操作

python - Opencv-在python中将图像转换为任意位深度

Eclipse 中的 C 代码返回对符号 cvSaveImage 的 undefined reference

python - 图像路径在 Django Admin 上返回 404

javascript - 将带有文件输入的多个图像上传到 Canvas 元素

c++ - opencv 与 netbeans C++ 链接器错误

python - 使用 pygsr 进行语音识别时出错