Raspberry pi のカメラでキャプチャした png の各ピクセルを調べて、特定の r、g、または b 値の上または下にあるピクセルを選択的に変更しようとしています。私はそれがかなり非効率的なアルゴリズムであることを知っています.Pythonスクリプトのコツをつかもうとしているだけです. 私は質問から@Constantinのコードに基づいてコードを作成しました: How can I read the RGB value of a given pixel in Python? 彼のコードは以下です。
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()
そして、私はこれを次のように変更しました:
#!/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 が 1、2 分考えてから、まったく同じ新しい png を開くことができます。スクリプトで何が欠けているのですか、または Raspbian Jessie でピクセル単位の処理を行うための Python よりも優れたプラットフォームはありますか?
どうもありがとう!