[英]matlplotlib with opencv gives a different image with the same pixel values
I've been trying to modify the pixels of an image slightly, but the colors are getting distorted. 我一直在尝试稍微修改图像的像素,但是颜色变得失真了。 So, I multiplied every pixel with 1 and saw the result.
因此,我将每个像素乘以1,然后看到结果。
Here's my code 这是我的代码
import numpy as np
from matplotlib import pyplot as plt
import cv2
mud1 = cv2.imread('mud.jpeg')
print mud1.shape
mask = np.random.random_integers(1,1,size=(81,81,3))
print mask.shape
print mask[21][21][2]
print mud1[21][21][2]
mud1new = np.multiply(mud1,mask)
print mud1new[21][21][2]
plt.subplot(121),plt.imshow(mud1),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(mud1new),plt.title('Masked')
plt.xticks([]), plt.yticks([])
plt.savefig('problem.jpeg')
plt.show()
The pixels remain unchanged but somehow the image I see is different. 像素保持不变,但是我看到的图像有所不同。
The issue is because np.random.random_integers
returns objects that are int64
whereas your loaded image is uint8
so when you multiply the two together, mud1new
becomes an int64
array. 问题是因为
np.random.random_integers
返回的对象是int64
而您加载的图像是uint8
所以当您将两者相乘时, mud1new
会成为一个int64
数组。 When using imshow
, it expects the following types 使用
imshow
,需要以下类型
- MxN – values to be mapped (float or int)
MxN –要映射的值(浮点数或整数)
- MxNx3 – RGB (float or uint8)
MxNx3 – RGB(浮点型或uint8)
- MxNx4 – RGBA (float or uint8)
MxNx4 – RGBA(浮点型或uint8)
To fix this, you should cast mud1new
as a uint8
prior to display with imshow
要解决此问题,在使用
imshow
显示之前,应将mud1new
为uint8
mud1new = mud1new.astype(np.unit8)
plt.imshow(mud1new)
You could also convert mud1new
to a float
but that would require that all of your values should be between 0 and 1 so you'd have to divide everything by 255. 您还可以将
mud1new
转换为float
但这将要求所有值都应介于0和1之间,因此您必须将所有值除以255。
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的范围内。
mud1new_float = mud1new.astype(np.float) / 255.0;
plt.imshow(mud1new_float)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.