파이썬에서 주어진 픽셀의 RGB 값을 읽는 방법은 무엇입니까?
로 이미지를 열면 open("image.jpg")
픽셀의 좌표가 있다고 가정하면 픽셀의 RGB 값을 어떻게 얻을 수 있습니까?
그런 다음 어떻게 반대로 할 수 있습니까? 빈 그래픽으로 시작하여 특정 RGB 값으로 픽셀을 '쓰기'하시겠습니까?
추가 라이브러리를 다운로드 할 필요가없는 경우 선호합니다.
파이썬 이미지 라이브러리 를 사용 하여이 작업을 수행 하는 것이 가장 좋습니다 . 별도의 다운로드입니다.
원하는 것을 수행하는 가장 쉬운 방법 은 배열과 같이 조작 할 수있는 픽셀 액세스 객체를 반환하는 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 은보다 포괄적 인 이미징 라이브러리이지만 훨씬 더 무겁습니다.
사용 베개 (2.7 이상 파이썬뿐만 아니라 파이썬 3.X와 함께 작동), 다음을 수행 할 수 있습니다 :
from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
이제 모든 픽셀 값이 있습니다. RGB이거나 다른 모드이면로 읽을 수 있습니다 im.mode
. 그러면 다음을 통해 픽셀 (x, y)
을 얻을 수 있습니다 .
pixel_values[width*y+x]
또는 Numpy를 사용하여 배열을 재구성 할 수 있습니다.
>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18 18 12]
완전하고 사용하기 쉬운 솔루션은
def get_image(image_path):
"""Get a numpy array of an image so that one can access values[x][y]."""
image = Image.open(image_path, 'r')
width, height = image.size
pixel_values = list(image.getdata())
if image.mode == 'RGB':
channels = 3
elif image.mode == 'L':
channels = 1
else:
print("Unknown mode: %s" % image.mode)
return None
pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
return pixel_values
Dave Webb가 말했듯이 :
Here is my working code snippet printing the pixel colours from an image:
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
There's a really good article on wiki.wxpython.org entitled Working With Images. The article mentions the possiblity of using wxWidgets (wxImage), PIL or PythonMagick. Personally, I've used PIL and wxWidgets and both make image manipulation fairly easy.
You can use pygame's surfarray module. This module has a 3d pixel array returning method called pixels3d(surface). I've shown usage below:
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
I hope been helpful. Last word: screen is locked for lifetime of screenpix.
Image manipulation is a complex topic, and it's best if you do use a library. I can recommend gdmodule which provides easy access to many different image formats from within Python.
install PIL using the command "sudo apt-get install python-imaging" and run the following program. It will print RGB values of the image. If the image is large redirect the output to a file using '>' later open the file to see RGB values
import PIL
import Image
FILENAME='fn.gif' #image can be in gif jpeg or png format
im=Image.open(FILENAME).convert('RGB')
pix=im.load()
w=im.size[0]
h=im.size[1]
for i in range(w):
for j in range(h):
print pix[i,j]
You could use the Tkinter module, which is the standard Python interface to the Tk GUI toolkit and you don't need extra download. See https://docs.python.org/2/library/tkinter.html.
(For Python 3, Tkinter is renamed to tkinter)
Here is how to set RGB values:
#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()
And get 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(" ")))
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('Cricket_ACT_official_logo.png')
imgplot = plt.imshow(img)
from PIL import Image
def rgb_of_pixel(img_path, x, y):
im = Image.open(img_path).convert('RGB')
r, g, b = im.getpixel((x, y))
a = (r, g, b)
return a
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.
참고URL : https://stackoverflow.com/questions/138250/how-to-read-the-rgb-value-of-a-given-pixel-in-python
'Programing' 카테고리의 다른 글
Xcode-그러나… 아카이브는 어디에 있습니까? (0) | 2020.07.11 |
---|---|
Laravel Eloquent 쿼리에서 테이블의 별칭을 지정하는 방법 (또는 쿼리 작성기를 사용하는 방법)? (0) | 2020.07.11 |
프로그래밍 방식으로 python.exe 위치를 얻는 방법? (0) | 2020.07.11 |
오늘 날짜에서 2 개월을 뺀 SQL 쿼리 (0) | 2020.07.11 |
Ctrl 및 커서 키를 누를 때 Visual Studio에서 CamelCase를 이해하도록합니다. (0) | 2020.07.11 |