python中使用PIL库对图片像素点遍历以及像素值改变

将图片中特定像素值的部分改为另一种像素值

实验目的:将一张图片中白色的部分变成蓝色,灰色的部分改成黄色…,使用了PIL库,PIL库只支持python2.X版本,在python3.X版本中被并到pillow库中,想要使用PIL要先导入pillow库,然后在代码引用from PIL import Image 即可。

在这里插入图片描述

读取图片的像素值

先对整个图片每个像素点的像素值进行遍历,PIL库需要将图像先转成numpy数组,img_array = np.array(img)或者img = np.asarray(image),后面存储处理好的新图像时要把数组转成图像, dst[h,w] = img_array[h,w],img2 = Image.fromarray(np.uint8(dst))。

改变颜色

将特定像素值的点改变颜色

height = shape[0]
width = shape[1]
dst = np.zeros((height,width,3))
for h in range(0,height):
    for w in range (0,width):
        (b,g,r) = img_array[h,w]
        if (b,g,r)==(255,255,255):#白色
            img_array[h,w] = (0,255,255)#蓝色

实验图片展示

左图为原始图像,右图为处理后的图像
在这里插入图片描述

完整代码

代码片.

from PIL import Image
import numpy as np
img = Image.open("F:/PYproject/unet_camvid/CamVid/testimage/2.png")
#img.show()
img_array = np.array(img)#把图像转成数组格式img = np.asarray(image)
shape = img_array.shape
print(img_array.shape)
for i in range(0,shape[0]):
    for j in range(0,shape[1]):
        value = img_array[i, j]
        #print("",value)
        if value[0] != 0:
            print("", value)
height = shape[0]
width = shape[1]
dst = np.zeros((height,width,3))
for h in range(0,height):
    for w in range (0,width):
        (b,g,r) = img_array[h,w]
        if (b,g,r)==(255,255,255):#白色
            img_array[h,w] = (0,255,255)#蓝色
        if (b, g, r) == (85, 85, 85):  # 深灰
            img_array[h, w] = (0, 128, 0)  # 绿色
        if (b, g, r) == (170, 170, 170):  # 灰色
            img_array[h, w] = (255, 255, 0)  # 黄色
        if (b, g, r) == (0, 0, 0):  # 黑色
            img_array[h, w] = (255, 0, 0)  # 红色
        dst[h,w] = img_array[h,w]
img2 = Image.fromarray(np.uint8(dst))
img2.show(img2)
img2.save("3.png","png")

  • 20
    点赞
  • 102
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值