python使用PIL和matplotlib获取图片像素点并合并解析

yipeiwu_com7年前Python基础

python 版本 3.x

首先安装 PIL

由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。

所以 安装:

pip install pillow

获取像素点

import numpy as np
from PIL import Image
img = Image.open("./b.png").convert('RGBA')
a_img = np.asarray(img)

获取的图片像素为 一个二维数组,相当于是二维左边系, x ,y 然后里面存了一个元组 值分别为 r g b a

分别计算改变了像素值之后,就需要将数据写入到图片了,这个时候就需要 matplotlib

import matplotlib.pyplot as plt
 
plt.figure("beauty") # 开启图层,名称为 beauty
plt.imshow(a_img) # 二维数组的数据
plt.axis('off')
#plt.show()
plt.savefig("./result.png")

下面给出一个完整的 demo

需要将两张图片合并计算,并输出结果:

将上面两个图片合并

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
def modeSuperposition(basePixel,mixPixel,alpha):
 basePixel = int(basePixel)
 mixPixel = int(mixPixel);
 res=0
 if basePixel <= 128 :
  res = int(mixPixel) * int(basePixel) / 128;
 else:
  res = 255 - (255 - mixPixel)*(255 - basePixel) / 128;  
 a = alpha / 255; 
 if a > 1:
  a = 1
 res = (1-a)*basePixel + a*res 
 t = int(res)&-256
 if t == 0:
  return int(res)
 if res > 255:
  return 255 
 return 0 
def mergePoint(x,y):
 p1 = img1[x][y]
 p2 = img2[x][y]
 p1[1] = modeSuperposition(p1[0],p2[0],p2[3])
 p1[2] = modeSuperposition(p1[1],p2[1],p2[3])
 p1[3] = modeSuperposition(p1[2],p2[2],p2[3])  
imgA = Image.open('./b.png')
img1=np.array(imgA.convert('RGBA')) #打开图像并转化为数字矩
img2=np.array(Image.open("./light.png").convert('RGBA'))  
i = len(img1);
j = len(img1[0]);
 
for k in range(0,len(img2)):
 for n in range(0,len(img2[0])):
  if k < i and n < j:
   mergePoint(k,n)  
#img = Image.new("RGBA",imgA.size)###创建一个5*5的图片
plt.figure("beauty") # 开启图层,名称为 beauty
plt.imshow(img1) # 二维数组的数据
plt.axis('off')
#plt.show()
plt.savefig("./result.png")

结果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈python中str字符串和unicode对象字符串的拼接问题

str字符串 s = '中文' # s: <type 'str'> s是个str对象,中文字符串。存储方式是字节码。字节码是怎么存的: 如果这行代码在python解释...

粗略分析Python中的内存泄漏

引子 之前一直盲目的认为 Python 不会存在内存泄露, 但是眼看着上线的项目随着运行时间的增长 而越来越大的内存占用, 我意识到我写的程序在发生内存泄露, 之前 debug 过 lo...

基于python生成器封装的协程类

自从python2.2提供了yield关键字之后,python的生成器的很大一部分用途就是可以用来构建协同程序,能够将函数挂起返回中间值并能从上次离开的地方继续执行。python2.5的...

wxPython:python首选的GUI库实例分享

wxPython:python首选的GUI库实例分享

wxPython是Python语言的一套优秀的GUI图形库,允许Python程序员很方便的创建完整的、功能健全的GUI用户界面。 wxPython是作为优秀的跨平台GUI库wxWidge...

Python生成8位随机字符串的方法分析

本文实例讲述了Python生成8位随机字符串的方法。分享给大家供大家参考,具体如下: #!/usr/bin/env python # -*- coding: utf-8 -*- im...