首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >打印图像中小于10,10,10的像素

打印图像中小于10,10,10的像素
EN

Stack Overflow用户
提问于 2012-10-24 21:25:48
回答 1查看 184关注 0票数 0

我是python的新手,希望大家能给我指出下一个方向。我正在使用PIL。做了相当多的研究,我还是被卡住了!

我需要得到每个像素的rgb,从0,0开始,沿着每一行一直到y坐标。这是一个bmp,只有黑白,但我只想让python打印10,10,10和0,0,0之间的像素。有人能给我一些建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-24 22:29:56

如果你确定所有像素都是r==g==b,那么这应该是可行的:

代码语言:javascript
运行
复制
from PIL import Image

im = Image.open("g.bmp")       # The input image. Should be greyscale
out = open("out.txt", "wb")    # The output.

data = im.getdata()            # This will create a generator that yields
                               # the value of the rbg values consecutively. If
                               # g.bmp is a 2x2 image of four rgb(12, 12, 12) pixels, 
                               # list(data) should be 
                               # [(12,12,12), (12,12,12), (12,12,12), (12,12,12)]

for i in data:                   # Here we iterate through the pixels.
    if i[0] < 10:                # If r==b==g, we only really 
                                 # need one pixel (i[0] or "r")

        out.write(str(i[0])+" ") # if the pixel is valid, we'll write the value. So for
                                 # rgb(4, 4, 4), we'll output the string "4"
    else:
        out.write("X ")          # Otherwise, it does not meet the requirements, so
                                 # we'll output "X"

如果由于某种原因不能保证r==g==b,请根据需要调整条件。例如,如果您希望平均值为10,则可以将条件更改为如下所示

代码语言:javascript
运行
复制
if sum(i) <= 30: # Equivalent to sum(i)/float(len(i)) <= 10 if we know the length is 3

另请注意,对于灰度格式的文件(与彩色文件格式中的灰度图像相反),im.getdata()将简单地将灰度作为单个值返回。因此,对于rgb(15, 15, 15)的2x2图像,list(data)将输出[4, 4, 4, 4]而不是[(4, 4, 4), (4, 4, 4), (4, 4, 4), (4, 4, 4)]。在这种情况下,在进行分析时,只需参考i而不是i[0]

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13050225

复制
相关文章

相似问题

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