opencv在numpy vectoriz之后显示黑色图像

2024-09-27 09:34:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用np的矢量化,但imshow显示的是一个黑色图像,如果我正确理解矢量化,它应该是白色的。我想问题出在outputtype,但我不能让它工作。在

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)

Tags: runtestimportselfdefnpcv2矢量化
1条回答
网友
1楼 · 发布于 2024-09-27 09:34:01

docs

The function imshow displays an image in the specified window. If the window was created with the CV_WINDOW_AUTOSIZE flag, the image is shown with its original size. Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth:

  • If the image is 8-bit unsigned, it is displayed as is.
  • If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
  • If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].

如果运行以下代码:

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

你会得到类似于:

^{pr2}$

所以你的第二个例子被256除,它是整数除法,取整为0。试试看

vfunc = np.vectorize(self.func,otypes=[np.uint8])

您还可以考虑将第一个数组替换为

arr = np.zeros((25,25), dtype='uint8')

相关问题 更多 >

    热门问题