问题描述
使用谷歌(和这个网站)我看到了一些类似的问题,但我的问题仍然存在:
using google (and this site) i have seen some similar questions but my problem is still here:
我想绘制一个图像(不读取文件),能够操纵该图像中每个像素的颜色."
"i want to draw an image (without reading a file) , being able to manipulate every single pixel's colour in that image."
我看到另一个问题,建议这样做:
i have seen another question where was suggested to do something like this:
from tkinter import *
A=Tk()
B=Canvas(A)
B.place(x=0,y=0,height=256,width=256)
for a in range(256):
for b in range(256):
B.create_line(a,b,a+1,b+1,fill=pyList[a][b])#where pyList is a matrix of hexadecimal strings
A.geometry("256x256")
mainloop()
事实上这回答了我的问题,但是......它非常慢.我应该如何处理 1920x1080 的图像?等我死?
in fact this answers my question but... it is extremely slow.what should i do with a 1920x1080 image ? wait for my death?
所以我要求执行与上述代码相同但更快的方式
so i am asking something to perform the same as the above code but in a faster way
我找到了一种改进 jsbueno 建议的方法的方法,在链接的页面中有解释:
i have found a way to improve the method suggested by jsbueno , it is explained in the page linked :
推荐答案
确实很棘手 --我以为您必须使用 Canvas 小部件,但它也无法访问 Pixels.不过,嵌入在画布中的图像项目确实有.Tkinter.PhotoImage 类确实有一个put"接受十六进制格式和像素坐标的颜色的方法:
It is indeed tricky --I thought you had to use a Canvas widget, but that has no access to Pixels either.Image items embedded in the Canvas do have, though. The Tkinter.PhotoImage classdoes have a "put" method that accepts a color in hex format and pixel coordinates:
from tkinter import Tk, Canvas, PhotoImage, mainloop
from math import sin
WIDTH, HEIGHT = 640, 480
window = Tk()
canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000")
canvas.pack()
img = PhotoImage(width=WIDTH, height=HEIGHT)
canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal")
for x in range(4 * WIDTH):
y = int(HEIGHT/2 + HEIGHT/4 * sin(x/80.0))
img.put("#ffffff", (x//4,y))
mainloop()
好消息是,即使以这种方式进行,更新也是实时"的:您在图像上设置像素,然后看到它们显示在屏幕上.
The good news is that even it being done this way, the updates are "live":you set pixels on the image, and see them showing up on screen.
这应该比在屏幕上绘制更高级别的线条快得多 -但是对于很多像素,它仍然会很慢,因为需要一个 Python 函数调用每个像素.任何其他直接操作像素的纯 Python 方式都会受到影响 - 唯一的出路是从 Python 代码中调用在本机代码中一次操作多个像素的基元.
This should be much faster than the way drawing higher level lines on screen -but for lots of pixels it still will be slow, due to a Python function call needed forevery pixel. Any other pure python way of manipulating pixels directly will suffer from that - the only way out is calling primitives that manipulate several pixels at a time in native code from your Python code.
一个很好的跨平台库,用于获取 2d 绘图,但文档也很差是开罗 - 它应该有比 Tkinter 的 Canvas 或 PhotoImage 更好的原语.
A nice cross-platform library for getting 2d drawing, however poorly documented as wellis Cairo - it would should have much better primitives than Tkinter's Canvas or PhotoImage.
这篇关于python tkinter:如何处理像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!