【问题标题】:Transform image into other将图像转换为其他
【发布时间】:2016-05-27 13:54:39
【问题描述】:

使用 PIL 和 tkinter,我正在尝试在图像的像素矩阵中进行一些操作,例如:

start = Image.open("gua.jpg")
sta  = start.load()
i,j = start.size
current = np.zeros((i,j,3))

for ix in range(i):
    for jx in range(j):
         current[ix,jx] = [elem*0.5 for elem in sta[ix,jx]]

current = np.asarray(current)
current = Image.fromarray(current, "RGB")
out = ImageTk.PhotoImage(current)

panel.configure(image = out)
panel.image = out

但即使我只是将图像像素矩阵中的信息传递给我的矩阵(current[ix,jx] = sta[ix,jx]),我的结果也是随机的,我做错了什么?

谢谢!

P.S:out = ImageTk.PhotoImage(start) 我可以毫无问题地做。

【问题讨论】:

  • 在您执行current = np.asarray(current) 之后,current 的实际外观如何? (打印出来并发布第一部分,我知道它会非常大)
  • 在循环内,我做print sta[ix,jx], current[ix,jx],这就是输出:(128, 128, 120) [ 128. 128. 120.] 将其转换为数组后,我得到:... [[ 179. 179. 177.] [ 174. 174. 172.] [ 167. 167. 165.] ..., [ 73. 68. 64.] [ 84. 70. 67.] [ 153. 133. 132.]] ...
  • 你期待什么?我的意思是你想做什么?

标签: python tkinter python-imaging-library


【解决方案1】:

你需要指定你的数组的dtypenp.uint8

current = np.zeros((i,j,3),dtype=np.uint8)

如果您在 PIL 对数组使用 .tobytes() 方法时未指定此项,则会获取对 "RGB" 没有意义的数据,因为它用于浮点数。

另请注意,fromarray 逐行获取数据,因此高度需要是数组的第一个维度,您可以通过在传递给fromarray 之前简单地获取transpose 来解决此问题:

img = Image.fromarray(current.transpose(1,0,2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 2012-09-26
    • 2023-03-25
    相关资源
    最近更新 更多