首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Raspbian上有选择地用PyPNG改变png像素

在Raspbian上有选择地用PyPNG改变png像素
EN

Stack Overflow用户
提问于 2016-04-08 21:02:49
回答 1查看 928关注 0票数 0

我试图检查我用Raspberry pi的相机捕捉到的png的每个像素,并有选择地更改高于或低于某个r、g或b值的像素。我知道这是一个效率很低的算法,我只是想了解一下python脚本。我的代码是基于@Constantin的代码的,问题是:如何读取Python中给定像素的RGB值?,他的代码在下面。

代码语言:javascript
复制
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()

我把它改成了这个

代码语言:javascript
复制
#!/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()

所发生的是圆周率思考了一两分钟,然后我可以打开一个新的png,完全相同。我的脚本遗漏了什么,或者在Raspbian上有一个比python更好的逐点处理平台?

非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-08 23:36:03

如果您对新库开放,我建议使用pillow,它是Python (PIL)的继任者。它要简单得多,而且不限于巴布亚新几内亚。文件在这里。

代码语言:javascript
复制
from PIL import Image, ImageDraw

img = Image.open('image.png')
img = img.convert("RGB") # Make sure we are in 8-bit RGB
draw = ImageDraw.Draw(img)

for y in range(img.height):
    for x in range(img.width):
        # getpixel returns a tuple with (R, G, B)
        if img.getpixel((x, y))[1] > 175: # If too green
            draw.point((x,y), '#000000') # Color syntax is CSS-like

img.save('test_edited.png', 'PNG')
# You can also use img.show() in a graphical environment
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36509305

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档