如何更改图像的像素值? [英] How to change the pixel values of an Image?

查看:152
本文介绍了如何更改图像的像素值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事图像处理项目,并且是Python和PIL的初学者.任何帮助将不胜感激.

I am working on an Image Processing Project and I am a beginner at Python and using PIL. Any help would be appreciated.

所以,我正在做的是,我有一个带有星星和噪音的空间图像.我想做的是仅保留较亮的像素,并滤除暗淡的像素.现在,这是我尝试消除噪声的基本步骤. 研究图像数据后,我发现205的值很可能是我想要保持阈值的值.

So, what I am doing is, I have an image of space with stars and noise. What I want to do is keep only the brighter pixels and filter out the dull ones. For now, this is my basic step at trying to remove the noise. After studying the image data, I found that values of 205 are quite possibly the ones I want to keep the threshold at.

所以我在代码中所做的是打开图像并将包含205的像素值更改为黑色. 这是相同的代码:

So what I am doing in the code is, open the image and change the pixel values containing 205 to black. Here is the code for the same:

from PIL import Image
im = Image.open('nuvfits1.png')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = im.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
           pixelMap[i,j] = (0,0,0,255)
        pixelsNew[i,j] = pixelMap[i,j]
im.close()
img.show()       
img.save("out.tif") 
img.close()

问题在于,生成的图像只是一个纯白色的屏幕.我做错了什么?

The problem is, that the resultant image is just a plain white screen. What have I done wrong?

推荐答案

if块之后应是else块,以便不符合您条件的正常"像素保留其原始值.

The if block should be followed by an else block, so that "normal" pixels that do not meet your criteria retain their original values.

from PIL import Image
im = Image.open('leaf.jpg')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
            pixelMap[i,j] = (0,0,0,255)
        else:
            pixelsNew[i,j] = pixelMap[i,j]
img.show()

上面的代码给了我以下结果:

The above code gave me the following results:

输入图片

输出图像

这篇关于如何更改图像的像素值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆