python - 使用 Pillow/numpy 在任何分割带上执行 .dot 后,无法合并分割图像

标签 python arrays python-2.7 numpy python-imaging-library

我正在尝试使用 Pillow 和 numpy 来校正图像中的颜色。将 im.split() 与 np.array 结合使用。

我想将红色波段中的所有颜色相乘,但找不到方法。

我尝试了各种方法,经过大量谷歌搜索后希望这将是解决方案:

from PIL import Image
import numpy as np

im=Image.open('test.jpg')
r,g,b=im.split() 

datar = np.array(r)
datag = np.array(g)
datab = np.array(b)

rm=0.4 # the value I would like to multiply all red pixels by

datar=datar.dot(rm) # this works, but turns the values in the array into floats
datar=datar.astype(int) # I was hoping this would solve it

im=Image.merge("RGB", (Image.fromarray(datar), Image.fromarray(datag), Image.fromarray(datab)))

我可以用数组做很多事情并且合并成功,但是尝试这样做会出现以下错误:

im=Image.merge("RGB", (Image.fromarray(datar), Image.fromarray(datag), Image.fromarray(datab)))
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2408, in merge
im.putband(bands[i].im, i)
ValueError: images do not match

应用 .dot 和 .astype(int) 之前和之后的数组看起来相同,并且值正确相乘。

最佳答案

Image.merge 失败,因为 RGB 图像的模式不同(请参阅 PIL Image modes )。您可以通过以下方式检查模式:

>>> Image.fromarray(datar).mode
'I'
>>> Image.fromarray(datag).mode
'L'

原因是 numpy 数组的类型:

>>> datar.dtype
dtype('int32')
>>> datag.dtype
dtype('uint8')

要解决这个问题,请替换它:

datar=datar.astype(int)

这样:

datar = datar.astype('uint8')

关于python - 使用 Pillow/numpy 在任何分割带上执行 .dot 后,无法合并分割图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39901043/

相关文章:

python - numpy 数组 : basic questions

javascript - 在单词数组中搜索单词

python-2.7 - ssl.py 中的 context.option 设置

python-2.7 - 我收到属性错误 : 'module' object has no attribute 'enableTrace' while running a python code

ios - Swift:每次出现 tableview 时如何重新加载新内容(例如数组)?

python - imp.load_source 另一个文件而不是 .py ,但 .py 也存在于该目录中

python - 读取压缩的 JSON 文件

Python lxml : Ignore XML declaration (errors)

Python,如果键已经存在,如何将键+数字添加到字典中

c++ - C++代码::Blocks “#include <array>” causing error