首页 > 解决方案 > 我想通过在 python 中传递元组列表来创建图像

问题描述

import numpy as np

from PIL  import Image

img=Image.open("Car.jpg")

array= np.array(img)

a = array

rgb=250,0,0

for  i  in  range(768):
      for  j  in  range(500):
             a[ i ] [ j ]=rgb

new_image=Image.fromarray(array)

new_image.save( "new.jpg" )

new_image.show()

我想传递像元组列表这样的 rgb 值:

rgb = [(255,0,0),
(198, 252, 247), (255, 255, 250) ,(254, 253, 248) ,(251, 252, 246), (247, 248, 240) ... 
(100, 144, 247), (255, 200, 250), (254, 253,0)]

和 rgb 值随 i 和 j 变化

a [ i ] [ j ] = rgb

标签: python

解决方案


您可以使用getdata()获得 RGB 。然后你可以自由地操纵每个像素。例如,您想要翻转图像。

from PIL import Image

# Resize for minimising pixels
width, height = 300, 200
src_image = ImageCall('cat.jpg').get_img()
src_image = src_image.resize((width, height), Image.ANTIALIAS)

# Get pixels in a list
pixels = list(src_image.getdata())
pixels = list(map(lambda i: i[::-1], pixels[:])) # Flipping
# pixels = [(r,g,b), (r,g,b), (r,g,b), (r,g,b), ..... n]

# Add new pixels to construct a new image
dst_image = Image.new('RGB', (width, height))
dst_image.putdata(pixels)  # Place pixels in the new image.
dst_image.save('result.png')  # Save the new image.

在此处输入图像描述

结果:

在此处输入图像描述


推荐阅读