Python opencv 过滤感兴趣区域之外的所有内容
Python opencv filtering everything outside region of interest
给定一张图像和一组点(点数 >= 3),其中这组点将形成一个多边形,这是我感兴趣的区域,我的目标是过滤该图像中外部的所有内容这个感兴趣的区域,而它里面的区域没有被触及。
例如,给定大小为 712 x 480 px
的图像和点数
[[120,160]
[100,130]
[120,100]
[140,130]]
我所做的是
#Create an array of object rect which represents the region of interest
rect = [[120,160], [100,130], [120,100],[140,130]]
mask = np.array([rect], dtype=np.int32)
#Create a new array filled with zeros, size equal to size of the image to be filtered
image2 = np.zeros((480, 712), np.int8)
cv2.fillPoly(image2, [mask],255)
在这一步之后,image2
将是一个数组,除了位置与我感兴趣的区域完全相同的区域外,其他任何地方都为 0。在这一步之后我所做的是:
output = cv2.bitwise_and(image, image2)
image
这是我的输入图像。我收到此错误:
cv2.error: ..\..\..\..\opencv\modules\core\src\arithm.cpp:1021: error: (-209) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function cv::binary_op
我真的不明白我在这里做错了什么。另外,我的问题有其他解决方案吗?我对 opencv 还是很陌生,并且仍在学习所有内容。如果有更好的do/library使用方法请指教。谢谢!
我刚刚找到 1 个解决问题的方法。所以不要写这个
output = cv2.bitwise_and(image, image2)
我先把 image2
变成一个二进制掩码,然后 bitwise_and
它和我的原始图像。所以代码应该是这样的
maskimage2 = cv2.inRange(image2, 1, 255)
out = cv2.bitwise_and(image, image, mask=maskimage2)
这样做将使感兴趣区域之外的所有内容的二进制值为 0。如果您发现任何缺陷,请发表评论。
给定一张图像和一组点(点数 >= 3),其中这组点将形成一个多边形,这是我感兴趣的区域,我的目标是过滤该图像中外部的所有内容这个感兴趣的区域,而它里面的区域没有被触及。
例如,给定大小为 712 x 480 px
的图像和点数
[[120,160]
[100,130]
[120,100]
[140,130]]
我所做的是
#Create an array of object rect which represents the region of interest
rect = [[120,160], [100,130], [120,100],[140,130]]
mask = np.array([rect], dtype=np.int32)
#Create a new array filled with zeros, size equal to size of the image to be filtered
image2 = np.zeros((480, 712), np.int8)
cv2.fillPoly(image2, [mask],255)
在这一步之后,image2
将是一个数组,除了位置与我感兴趣的区域完全相同的区域外,其他任何地方都为 0。在这一步之后我所做的是:
output = cv2.bitwise_and(image, image2)
image
这是我的输入图像。我收到此错误:
cv2.error: ..\..\..\..\opencv\modules\core\src\arithm.cpp:1021: error: (-209) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function cv::binary_op
我真的不明白我在这里做错了什么。另外,我的问题有其他解决方案吗?我对 opencv 还是很陌生,并且仍在学习所有内容。如果有更好的do/library使用方法请指教。谢谢!
我刚刚找到 1 个解决问题的方法。所以不要写这个
output = cv2.bitwise_and(image, image2)
我先把 image2
变成一个二进制掩码,然后 bitwise_and
它和我的原始图像。所以代码应该是这样的
maskimage2 = cv2.inRange(image2, 1, 255)
out = cv2.bitwise_and(image, image, mask=maskimage2)
这样做将使感兴趣区域之外的所有内容的二进制值为 0。如果您发现任何缺陷,请发表评论。