从列表制作图像 - python

我正在尝试从Python中的1和0列表创建图像。

from PIL import Image

img1 = Image.open('Image1.gif') #the image is strictly black and white
img1_size = img1.size 
img1_k = []
for i in range(img1_size[0]): 
    for j in range(img1_size[1]): 
        tmp_pix = img1.getpixel((i,j))
        if (tmp_pix>127): 
            img1_k.append(1)
        else:
            img1_k.append(0)


img = Image.new('RGB', (img1_size[1],img1_size[0]), "white") 
cmap = {1: (255,255,255),
        0: (0,0,0)}
data = [cmap[i] for i in img1_k]
img.putdata(data)
img.show()             
img.save('Image2.png')

但是,代替原始图像:

从列表制作图像 - python

代码产生旋转和反转的图像:

从列表制作图像 - python

我猜测putdata()的格式与我获取列表像素的方式不同。我怎样才能得到正确的图片?

参考方案

getpixelputpixel基于x-y坐标,而getdataputdata基于行列。

首先,您需要基于img_k行-列:

for j in range(img1_size[1]):     # row (y)
    for i in range(img1_size[0]): # column (x)
        tmp_pix = img1.getpixel((i,j))
        if tmp_pix > 127:
            img1_k.append(1)
        else:
            img1_k.append(0)

其次,您需要创建x * y尺寸的图像:

img = Image.new('RGB', (img1_size[0], img1_size[1]), "white")  # <--
# OR  Image.new('RGB', img1.size, "white") 
cmap = {1: (255,255,255),
        0: (0,0,0)}
data = [cmap[i] for i in img1_k]
img.putdata(data)
img.show()             
img.save('Image2.png')

顺便说一句,通过使用getpixelputdata而不是混合getdataputdata,代码可以更简单:

from PIL import Image

img1 = Image.open('Image1.gif')
data = [(255, 255, 255) if pixel > 127 else (0, 0, 0) for pixel in img1.getdata()]
img = Image.new('RGB', img1.size, "white") 
img.putdata(data)
img.show()             
img.save('Image2.png')

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…