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

您所在的位置:网站首页 python图像颜色替换右半边 python中使用PIL库对图片像素点遍历以及像素值改变

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

2024-07-12 19:00| 来源: 网络整理| 查看: 265

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")


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3