で画像を開いた場合open("image.jpg")
、ピクセルの座標があると仮定して、ピクセルのRGB値を取得するにはどうすればよいですか?
次に、これを逆にするにはどうすればよいですか?空白のグラフィックから始めて、特定のRGB値でピクセルを「書き込み」ますか?
追加のライブラリをダウンロードする必要がない方がいいと思います。
Python Image Libraryを使用してこれを行うのがおそらく最善ですが、これは別のダウンロードであると思います。
必要なことを行う最も簡単な方法は、配列のように操作できるピクセルアクセスオブジェクトを返すImageオブジェクトのload()メソッドを使用することです。
from PIL import Image
im = Image.open('dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size # Get the width and hight of the image for iterating over
print pix[x,y] # Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)
im.save('alive_parrot.png') # Save the modified pixels as .png
または、画像を作成するためのはるかに豊富なAPIを提供するImageDrawを見てください。
PyPNG-軽量PNGデコーダー/エンコーダー
質問はJPGを示唆していますが、私の答えが一部の人々に役立つことを願っています。
PyPNGモジュールを使用してPNGピクセルを読み書きする方法は次のとおりです。
import png, array
point = (2, 10) # coordinates of pixel to be painted red
reader = png.Reader(filename='image.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
pixel_position = point[0] + point[1] * w
new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)
pixels[
pixel_position * pixel_byte_width :
(pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)
output = open('image-with-red-dot.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)
output.close()
PyPNGは、テストとコメントを含む、4000行未満の単一の純粋なPythonモジュールです。
PILは、より包括的なイメージングライブラリですが、かなり重いものでもあります。
デイブウェッブが言ったように:
これが、画像からピクセルの色を印刷する私の作業コードスニペットです。
import os, sys import Image im = Image.open("image.jpg") x = 3 y = 4 pix = im.load() print pix[x,y]
photo = Image.open('IN.jpg') #your image
photo = photo.convert('RGB')
width = photo.size[0] #define W and H
height = photo.size[1]
for y in range(0, height): #each pixel has coordinates
row = ""
for x in range(0, width):
RGB = photo.getpixel((x,y))
R,G,B = RGB #now you can use the RGB value
pygameのsurfarrayモジュールを使用できます。このモジュールには、pixels3d(surface)と呼ばれる3dピクセル配列を返すメソッドがあります。以下に使用法を示しました。
from pygame import surfarray, image, display
import pygame
import numpy #important to import
pygame.init()
image = image.load("myimagefile.jpg") #surface to render
resolution = (image.get_width(),image.get_height())
screen = display.set_mode(resolution) #create space for display
screen.blit(image, (0,0)) #superpose image on screen
display.flip()
surfarray.use_arraytype("numpy") #important!
screenpix = surfarray.pixels3d(image) #pixels in 3d array:
#[x][y][rgb]
for y in range(resolution[1]):
for x in range(resolution[0]):
for color in range(3):
screenpix[x][y][color] += 128
#reverting colors
screen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen
display.flip() #update display
while 1:
print finished
お役に立てば幸いです。最後の言葉:screenpixの存続期間中、画面はロックされます。
画像操作は複雑なトピックであり、ライブラリを使用するのが最適です。Python内からさまざまな画像形式に簡単にアクセスできるgdmoduleをお勧めします。
wiki.wxpython.org にWorking With Imagesという非常に優れた記事があります。この記事では、wxWidgets (wxImage)、PIL、または PythonMagick を使用する可能性について言及しています。個人的には、PIL と wxWidgets を使用しており、どちらも画像操作がかなり簡単です。
Tk GUI ツールキットへの標準 Python インターフェイスである Tkinter モジュールを使用でき、追加のダウンロードは必要ありません。https://docs.python.org/2/library/tkinter.htmlを参照してください。
(Python 3 の場合、Tkinter は tkinter に名前が変更されます)
RGB 値を設定する方法は次のとおりです。
#from http://tkinter.unpythonic.net/wiki/PhotoImage
from Tkinter import *
root = Tk()
def pixel(image, pos, color):
"""Place pixel at pos=(x,y) on image, with color=(r,g,b)."""
r,g,b = color
x,y = pos
image.put("#%02x%02x%02x" % (r,g,b), (y, x))
photo = PhotoImage(width=32, height=32)
pixel(photo, (16,16), (255,0,0)) # One lone pixel in the middle...
label = Label(root, image=photo)
label.grid()
root.mainloop()
RGB を取得します。
#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py
def getRGB(image, x, y):
value = image.get(x, y)
return tuple(map(int, value.split(" ")))
If you are looking to have three digits in the form of an RGB colour code, the following code should do just that.
i = Image.open(path)
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size
all_pixels = []
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
all_pixels.append(cpixel)
This may work for you.