简体   繁体   English

plt.imshow()无法正确显示numpy矩阵

[英]plt.imshow() not showing numpy matrix correctly

I'm having trouble drawing a rectangle on an image with OpenCV, and then displaying the image with matplotlib. 我在使用OpenCV在图像上绘制矩形时遇到麻烦,然后在使用matplotlib显示图像时遇到了麻烦。 This code in a Jupyter Notebook results in a black image being displayed, with no green rectangle: Jupyter Notebook中的以下代码导致显示黑色图像,没有绿色矩形:

import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

%matplotlib inline
image = np.zeros((720, 1280, 3))
cv2.rectangle(image, (100,100), (200,200), color=(0,255,0), thickness=2) # Green
plt.imshow(image)

I believe I can see the rectangle if I display the image with cv2.imshow() , but I don't know that OpenCV images can be displayed inline in Jupyter Notebooks like matplotlib images can. 我相信如果我使用cv2.imshow()显示图像,可以看到矩形,但是我不知道OpenCV图像可以像Matplotlib图像一样在Jupyter Notebook中内嵌显示。

EDIT: I think what's really going on is explained in this excerpt from the documentation : 编辑:我认为真正发生了什么在本文档摘录中得到解释:

The value for each component of MxNx3 and MxNx4 float arrays should be in the range 0.0 to 1.0. MxNx3和MxNx4浮点数组的每个组件的值应在0.0到1.0的范围内。

It can handle values between 0 and 255 if it's an integer array. 如果是整数数组,则可以处理0到255之间的值。

By default when you create a numpy array using np.zeros() or np.ones() , the default data type of the matrix is set to be float, or more precisely np.float64 , And there seems to be some problem in matplotlib to render a matrix with float data type (As per convention the RGB values in an image are always integral, so we can't blame matplotlib for this.) 默认情况下,当您使用np.zeros()np.ones()创建numpy数组时,矩阵的默认数据类型设置为float,或更准确地说是np.float64 ,并且matplotlib中似乎存在一些问题渲染具有float数据类型的矩阵(按照惯例,图像中的RGB值始终是整数,因此我们不能为此而归咎于matplotlib。)

Now you have 2 options: 现在,您有2个选择:

  • Create the numpy matrix with np.uint8 datatype 使用np.uint8数据类型创建numpy矩阵

     image = np.zeros((720, 1280, 3), dtype = np.uint8) 
  • Convert the matrix in integral type before rendering it on plt. 在将其渲染到plt之前,将其转换为整数类型。

     image = np.astype(image, np.uint8) 

Also you need to add plt.show() at the end. 另外,您还需要在最后添加plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM