Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

python - How can I grab the color of a pixel on my desktop? (Linux)

I want to grab the color of a pixel with known coordinates on my Linux desktop.

Until now, I've used "import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg" then extracting the pixel value using Python and PIL.

This does the job, but since import grabs the whole window before cropping, it's very slow :(

Are there any clever way to grab the color of only one pixel? I know both relative (window) and absolute coordinates.

A Python or shell script would be preferable, but if you know some clever C/X11 functions, also please let me know :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This does the trick, but requires python-gtk:

import gtk.gdk
import sys

def PixelAt(x, y):
    w = gtk.gdk.get_default_root_window()
    sz = w.get_size()
    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
    pixel_array = pb.get_pixels_array()
    return pixel_array[y][x]

print PixelAt(int(sys.argv[1]), int(sys.argv[2]))

On Ubuntu 9.10, this also requires python-numpy or it segfaults the python interpreter on the get_pixels_array line. Ubuntu 10.04 it still has this requirement, or it causes an ImportError regarding numpy.core.multiarray.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...