python - 你如何比较像素?

标签 python python-imaging-library

我正在使用 PIL 拍摄一张黑色背景的图像,然后用它制作一个蒙版。我想让程序做的是遍历图像中的所有像素,如果像素是黑色,则将其设为白色,如果是任何其他颜色,则将其设为黑色,但我不确定如何适本地比较像素值以确定什么与像素有关。

到目前为止,这是我创建全黑图像的代码。

import os, sys
import Image

filename = "C:\Users\pdiffley\Dropbox\C++2\Code\Test\BallSpriteImage.bmp"
height   = 50
width    = 50


im = Image.open(filename)
im = im.load()

i = 0
j = 0
while i<height:
    while j<width:
        if im[j,i] == (0,0,0):
            im[j,i] = (255,255,255)
        else:
            im[j,i] = (0,0,0) 
        j = j+1
    i = i+1
mask = Image.new('RGB', (width, height))
newfile = filename.partition('.')
newfile = newfile[0] + "Mask.bmp"

mask.save(newfile)

我认为问题在于将 im[j,i] 与 RGB 值 (0,0,0) 进行比较的 if 语句,该语句的计算结果始终为 false。比较像素的正确方法是什么?

最佳答案

像素数据比较正确。但是逻辑上有两个问题:

  1. 完成一行后,应将 j 重置为 0。
  2. 您正在修改对象“im”,但写的是“mask”。

这应该有效(只要您没有 alpha channel - 正如 andrewdski 指出的那样):

img = Image.open(filename)
im = img.load()

i = 0
while i<height:
    j = 0
    while j<width:
        if im[j,i] == (0,0,0):
            im[j,i] = (255,255,255)
        else:
            im[j,i] = (0,0,0) 
        j = j+1
    i = i+1
newfile = filename.partition('.')
newfile = newfile[0] + "Mask.png"

img.save(newfile)

关于python - 你如何比较像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6088664/

相关文章:

python - PIL 图像对象是否可变?

python - 如何在 python 中更改图像的 HSV 值?

python - 迭代 python 循环直到上一个位置的有效方法

javascript - 通过客户端javascript访问服务器中的sqlite

python-3.x - Python 图像保存错误 - 从 e ValueError : unknown file extension: 引发 ValueError ("unknown file extension: {}".format(ext))

python - 如何在存储到磁盘之前使用 Pillow-python 获取以 KB 为单位的图像大小?

python - 使用 python 的字符串格式化库的问题

python - 找不到文件错误 : [Errno 2] No such file or directory: 'hdfs' : 'hdfs' using subprocess popen in crontab

python - 如何在 python 中绘制 4 维数据的 kmeans 聚类?

python - PIL 安装失败缺少 :stdarg. h