Python图像编程(一)

PIL

PIL(Python Imaging Library)是Python图像处理模块,支持多种格式,提供强大图像处理能力,可通过pip安装,PIL仅支持到Python 2.7,但pillow完美支持Python3,pillow实在PIL基础上创建的兼容版本,可以直接安装pillow。
如果安装了anaconda可以直接使用pillow。

 pip install pillow

简单操作

如果安装了Anaconda3,可以在\Anaconda3\Lib\site-packages\PIL查看具体模块。
在windows环境下im.show使用windows自带的图像显示,可以使用matplotlib显示图像
以下代码可以改变plt.imshow(img12)中的参数查看图像效果

from PIL import Image
im = Image.open('C:\\Users\\WilliamZhang\\pythonLearn\\1.png')
im.show();
print(im.format)
print(im.size)
print(im.getpixel((100,50)))
print(im.histogram())

Python图像编程(一)

from PIL import Image
from random import randint as rint
img = Image.open('C:\\Users\\WilliamZhang\\pythonLearn\\test.bmp');
for w in range(200,280):
  for h in range(100,200):
    r = rint(0,255)
    g = rint(0,255)
    b = rint(0,255)
    img.putpixel((w,h),(r,g,b))
# img.show()
for w in range(200,280):
  for h in range(100,200):
    color = img.getpixel((w,h))
    img.putpixel((w+200,h),color)
img.show();

test.bmp是一张空白图片,利用随机数生成随机图,并移动200px
Python图像编程(一)

from PIL import Image
from PIL import ImageFilter
from PIL import ImageEnhance
from matplotlib import pyplot as plt
im = Image.open('C:\\Users\\WilliamZhang\\pythonLearn\\1.png')
# 缩放,重新生成一张图片
img1 = im.resize((100,100))
# rotate任意角度旋转,transpose支持特殊角度旋转
img2 = im.rotate(90)
img3 = im.transpose(Image.FLIP_TOP_BOTTOM)
img4 = im.transpose(Image.FLIP_LEFT_RIGHT)
img5 = im.transpose(Image.ROTATE_180)
# 图像增强
img6 = im.filter(ImageFilter.DETAIL)
# 图像模糊
img7 = im.filter(ImageFilter.BLUR)
# 边缘提取
img8 = im.filter(ImageFilter.FIND_EDGES)
# plt.imshow(img8)
# 点运算,整体变亮变暗
img9 = im.point(lambda i:i*1.3)
img10 = im.point(lambda i:i*0.7)
# 或使用图像增强模块ImageEnhance 增强对比度
enh = ImageEnhance.Contrast(im)
img11 = enh.enhance(1.3)
# 冷暖色调调整
r,g,b = im.split()
r = r.point(lambda i:i*1.3)
g = g.point(lambda i:i*0.9)
b = b.point(lambda i:0)
img12 = Image.merge(im.mode,(r,g,b))
plt.imshow(img12)
plt.show()

冷暖色调调整图片,剩下的可以修改plt.imshow(img12)查看相应效果
Python图像编程(一)
图片增强的效果,整体变亮1.3倍
Python图像编程(一)
图片整体变暗的效果
Python图像编程(一)
图片模糊的效果
Python图像编程(一)
边缘检测
Python图像编程(一)
刚开始学习,记录一下。