numpy矢量化后,opencv显示黑色图像 [英] opencv show black image after numpy vectorize

查看:140
本文介绍了numpy矢量化后,opencv显示黑色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用np的vectorize,但是imshow显示的是黑色图像,如果我正确理解vectorize的话,它应该是白色的.我认为问题是输出类型,但我无法使其正常工作.

i am trying to use np's vectorize but imshow is showing a black image where it should be white if i understand vectorize correctly. i think the problem is the outputtype but i cant get it to work.

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标志创建的,图像是 以其原始大小显示.否则,图像将缩放以适合 窗户.该功能可能会缩放图像,具体取决于其深度:

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:

  • 如果图像是8位无符号的,则按原样显示.
  • 如果图像是16位无符号或32位整数,则将像素除以256.即,值范围[0,255 * 256]映射到[0,255].
  • 如果图像为32位浮点,则像素值将乘以255. 是,值范围[0,1]映射到[0,255].
  • 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

您会得到类似的东西:

float64
int32
int32

因此您的第二种情况被256除,并且是整数除,四舍五入为0.请尝试

So your second case is divided by 256, and it being integer division, it rounds off to 0. Try with

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

,您可能还需要考虑将第一个数组替换为

and you may also want to consider replacing the first array with

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

这篇关于numpy矢量化后,opencv显示黑色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆