Raspberry pi'nin kameramla yakaladığım png'nin her bir pikselinden geçmeye çalışıyorum ve belirli bir r, g veya b değerinin üstünde veya altında olan pikselleri seçici olarak değiştiriyorum . Oldukça verimsiz bir algoritma olduğunu biliyorum, sadece python betiklerinin asılmasına çalışıyorum. Kodumu @ Constantin'ın kodundan şu sorudan aldım: How can I read the RGB value of a given pixel in Python? Onun kodu aşağıdadır.Raspbian'daki PyPNG ile png piksellerini seçici olarak değiştirme
ne olur#!/usr/bin/python
import png, array
reader = png.Reader(filename='test.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
for x in range(w):
for y in range(h):
point_index = x+(y-1)*w#This is the bit that I said I'd fix above.
r = pixels[point_index * pixel_byte_width + 0]
g = pixels[point_index * pixel_byte_width + 1]
b = pixels[point_index * pixel_byte_width + 2]
pixel = pixels[point_index * pixel_byte_width :
(point_index+1) * pixel_byte_width]
#Above we have all the info about each byte, and below is our devious plan
new_pixel = (0, 0, 0, 0) if metadata['alpha'] else (0, 0, 0)
#if g > 175:
pixel = array.array('B', new_pixel)
output = open('test_edited.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)
output.close()
pi bir iki dakika düşünür, sonra ben de aynı olan yeni bir png açabiliriz:
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
#The line below is, I think wrong. I'll point out the what I did in my code below
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()
Ve bu değiştirdim. betiğimde ne eksik, yoksa Python'dan daha iyi bir platform var mı?
Çok teşekkürler!
Cevabınız için teşekkürler, ne yazık ki hem Yastık hem de PIL Jessie deposunda bulunmuyor. –
@Dan P Hayır, ancak yastık PyPI'de (Python Paket Dizini), yani "pip install pillow" ile kolayca yüklenebilecekleri anlamına gelir. –
Oh elbette yeterli! Bu harika. Çok teşekkür ederim. Yastık ve PIL hakkında nerede okudum bilmiyorum. –