【发布时间】:2021-02-14 11:52:55
【问题描述】:
我是一位经验丰富的程序员,但对 Python 和 OpenCV 的经验有限。我正在裁剪电影帧,尝试使用电影的可见穿孔和边缘作为参考。附加的是单个帧(原始 1920 x 1080)和从该帧派生的掩码,在下面的代码中传递给 findcountours。 FindContours 找到 3 个轮廓,但只有最大的(右帧边界)是正确的,其他两个(驱动器穿孔)未正确检测到。你们哪位好心人能告诉我我做错了什么,并指出我的方向吗?
我正在使用 Python 3.8 和相关版本的 cv2。
这是sample frame 和mask 使用下面的代码派生的。
谢谢
克里斯
for file in args.files:
idx += 1
if os.path.isfile(file):
# load the input image (whose path was supplied via command line
# argument) and display the image to our screen
image = cv2.imread(file)
if image is None:
print('Could not open or find the image: ', args["image"])
fileinput.close()
exit(0)
image_clone = image.copy()
image_height = image.shape[0]
image_width = image.shape[1]
"""
Threshold image
"""
hsv = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2HSV)
#
# # define range of white color in HSV
# # change it according to your need !
lower_white = np.array([0, 0, 235], dtype=np.uint8)
upper_white = np.array([0, 0, 255], dtype=np.uint8)
#
# Threshold the HSV image to get only white colors
mask = cv2.inRange(hsv, lower_white, upper_white)
mask = cv2.copyMakeBorder(mask, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=[0, 0, 0])
# I have seen some spurious pixels so I filter
se1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se1, iterations = 5)
# Make sure I get rid of noise
mask = cv2.GaussianBlur(mask, (5, 5), 0)
cny = cv2.Canny(mask.copy(), 255/3, 255)
mask = cv2.bitwise_xor(mask, cny)
cv2.imwrite(os.path.splitext(file)[0] + '_mask_' + str(idx) + '.tif', mask)
dsize = (int(mask.shape[1] * (50 / 100)), int(mask.shape[0] * (50 / 100)))
# # # # # #
cv2.imshow("Mask Image", cv2.resize(mask.copy(), dsize))
cv2.waitKey(0)
cv2.destroyWindow("Mask Image")
contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
#
new_image = np.zeros((mask.shape[0], mask.shape[1]), np.uint8) * 0
#
cv2.drawContours(new_image, [max(contours, key=cv2.contourArea)], -1, 255, thickness=-1)
dsize = (int(new_image.shape[1] * (50 / 100)), int(new_image.shape[0] * (50 / 100)))
# # # # # # #
cv2.imshow("Mask Image", cv2.resize(new_image.copy(), dsize))
cv2.waitKey(0)
cv2.destroyWindow("Mask Image")
【问题讨论】: