Python opencv在numpy矢量化后显示黑色图像
我试图使用np的矢量化,但imshow显示的是一个黑色图像,如果我正确理解矢量化,它应该是白色的。我认为问题在于输出类型,但我无法让它工作Python opencv在numpy矢量化后显示黑色图像,python,opencv,numpy,Python,Opencv,Numpy,我试图使用np的矢量化,但imshow显示的是一个黑色图像,如果我正确理解矢量化,它应该是白色的。我认为问题在于输出类型,但我无法让它工作 import numpy as np import cv2 class Test(): def run(self): arr = np.zeros((25,25)) arr[:]=255 cv2.imshow('white',arr) flatarr = np.resha
import numpy as np
import cv2
class Test():
def run(self):
arr = np.zeros((25,25))
arr[:]=255
cv2.imshow('white',arr)
flatarr = np.reshape(arr,25*25)
vfunc = np.vectorize(self.func)
#vfunc = np.vectorize(self.func,otypes=[np.int])#same effect
flatres = vfunc(flatarr)
shouldbewhite = np.reshape(flatres,(25,25))
cv2.imshow('shouldbewhite',shouldbewhite)
def func(self,a):
return 255
cv2.namedWindow('white',0)
cv2.namedWindow('shouldbewhite',0)
a = Test()
a.run()
cv2.waitKey(0)
从:
imshow函数在指定窗口中显示图像。如果
窗口是使用CV_window_AUTOSIZE标志创建的,图像为
显示其原始大小。否则,将缩放图像以适合
窗户。该功能可根据图像的深度缩放图像:
- 如果图像是8位无符号的,它将按原样显示
- 如果图像是16位无符号或32位整数,则像素除以256。也就是说,值范围[0255*256]被映射到[0255]
- 如果图像是32位浮点,则像素值将乘以255。那个 即,值范围[0,1]映射到[0255]
class Test():
def run(self):
arr = np.zeros((25,25))
arr[:]=255
print arr.dtype
flatarr = np.reshape(arr,25*25)
vfunc = np.vectorize(self.func)
flatres = vfunc(flatarr)
print flatres.dtype
shouldbewhite = np.reshape(flatres,(25,25))
print shouldbewhite.dtype
def func(self,a):
return 255
您将得到如下结果:
float64
int32
int32
第二种情况是除以256,它是整数除法,四舍五入为0。试一试
vfunc = np.vectorize(self.func,otypes=[np.uint8])
,您还可以考虑用
替换第一个数组。arr = np.zeros((25,25), dtype='uint8')
作为补充说明,您不需要展平(重塑)阵列即可使用矢量化。例如,这可以
矢量化(lambda x:x+1)([[1,2],[3,4]])==数组([[2,3],[4,5]])
哇!你是对的!这是非常有用的。谢谢