我遇到的问题是,当馈入二进制图像时,像cv2.detectAndCompute,cv2.HoughlinesP这样的cv2方法会由于深度错误或NoneType而失败。
例如在下面的
def high_blue(B, G):
if (B > 70 and abs(B-G) <= 15):
return 255
else:
return 0
img = cv2.imread(os.path.join(dirPath,filename))
b1 = img[:,:,0] # Gives **Blue**
b2 = img[:,:,1] # Gives Green
b3 = img[:,:,2] # Gives **Red**
zlRhmn_query = np.zeros((2400, 2400), dtype=np.uint8)
zlRhmn_query[300:2100, 300:2100] = 255
zlRhmn_query[325:2075, 325:2075] = 0
cv2.imwrite('zlRhmn_query.jpg',zlRhmn_query)
zl_Rahmen_bin = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
zl_Rahmen_bin = np.vectorize(high_blue)
zl_Rahmen_bin = zl_Rahmen_bin(b1, b2)
cv2.imwrite('zl_Rahmen_bin.jpg',zl_Rahmen_bin)
sift = cv2.xfeatures2d.SIFT_create()
kp_query, des_query = sift.detectAndCompute(zlRhmn_query,None)
kp_train, des_train = sift.detectAndCompute(zl_Rahmen_bin,None)
只有zl_Rahmen_bin的最后一行因深度不匹配错误而失败。奇怪的是zlRhmn_query不会引发任何错误。
接下来,当我使用此处给出的框架化片段[http://opencvpython.blogspot.de/2012/05/skeletonization-using-opencv-python.html]并将框架传递给HoughLinesP时,我得到了类型为NoneType的lines对象。在检查时,我注意到骨架数组也是二进制的,即0或255。
请指教。
最佳答案
我一生中编写了50行Python,所以如果我在这里弄错了,请原谅。
zl_Rahmen_bin = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
您刚刚创建了一个由零填充的二维数组。
zl_Rahmen_bin = np.vectorize(high_blue)
现在,您立即将另一个值(一个函数)分配给相同的变量,这使得第一行变得过时了。
zl_Rahmen_bin = zl_Rahmen_bin(b1, b2)
据我了解,您刚刚调用了函数z1_Rahmen_bin并提供了蓝色和绿色图像作为输入。输出应该是另一个2d数组,其值为0或255。
我想知道np.vectorize如何知道输出应该是哪种数据类型。正如您显然需要uint8。 documentation表示,如果未指定类型,则通过使用第一个参数调用该函数来确定。因此,我猜在此示例中,默认类型为255或0。
而z1_Rahmen_bin.dtype实际上是np.uint32。
所以我修改了这个:
zl_Rahmen_bin = np.vectorize(high_blue)
至
zl_Rahmen_bin = np.vectorize(high_blue, otypes=[np.uint8])
这似乎可以做到。
也许仅仅做就足够了
z1_Rahmen_bin.dtype = np.uint8
但是正如我说的,我对Python一无所知...
关于python - cv2是否接受二进制图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45349717/