python - 带有 opencv 的 matplotlib 给出具有相同像素值的不同图像

标签 python opencv matplotlib

我一直在尝试稍微修改图像的像素,但颜色越来越失真。所以,我将每个像素乘以 1 并看到了结果。 enter image description here

这是我的代码

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()

像素保持不变,但我看到的图像不知何故不同。

最佳答案

问题是因为 np.random.random_integers 返回的对象是 int64 而您加载的图像是 uint8 所以当您将两者相乘时mud1new 一起变成了一个 int64 数组。使用 imshow 时,它需要以下类型

  • MxN – values to be mapped (float or int)
  • MxNx3 – RGB (float or uint8)
  • MxNx4 – RGBA (float or uint8)

要解决此问题,您应该在使用 imshow 显示之前将 mud1new 转换为 uint8

mud1new = mud1new.astype(np.unit8)
plt.imshow(mud1new)

您还可以将 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.

mud1new_float = mud1new.astype(np.float) / 255.0;
plt.imshow(mud1new_float)

关于python - 带有 opencv 的 matplotlib 给出具有相同像素值的不同图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41857467/

相关文章:

python - 如何在boto3中为AWS EC2实例设置标签

python - 处理不包含 XML 命名空间的 XPath 查询?

python - 如何在 OpenCV-Python 中打开带有 alpha channel 的图像?

java - 应用像素级操作很慢

python - 我在 matplotlib (python) 中有一个带有误差线的条形图,但我想要误差线在中间。我该怎么做呢?谢谢

python - Django 1.5 终于不安全了?

python - 如何通过 python 脚本 selenium 单击按钮( Angular )

python - cv2.kmeans 参数错误-python

python - 使用 pandas.cut() 并将其设置为数据帧的索引

python - 掩盖圆形区域的流图