【发布时间】:2019-10-29 10:39:38
【问题描述】:
我正在尝试使用 OpenCV 使用颜色从图像中提取对象,我尝试通过结合cv2.findContours() 的逆阈值和灰度,但我无法递归使用它。此外,我无法弄清楚如何从原始图像中“剪切”匹配并将其保存到单个文件中。
编辑
~
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 为上图。
这是我想出的,唯一的缺点是,我有第三张图片,而不是现在预期的 2 张显示阴影区域...
【问题讨论】:
-
您能详细说明您要达到的目标吗?
-
我正在尝试将每个“蓝色”的东西保存在一个单独的文件中
标签: python opencv image-processing deep-learning computer-vision