一,打开图片并查看图片基本信息(Image)
from PIL import Image
image = Image.open("../input/2.jpg")
print(image)
print("文件名:" + image.filename)
print("文件格式:" + image.format)
print("文件色彩模式:" + image.mode)
print("文件名大小(尺寸):" + str(image.size))
print("文件信息:" + str(image.info))
二,图像通道分离与合并(Image)
from PIL import Image
image1 = Image.open("../input/1.png")
image2 = Image.open("../input/3.jpg")
image2 = image2.resize(image1.size)
r1,g1,b1 = image1.split()
r2,g2,b2 = image2.split()
tmp = [r1,g2,b1]
img = Image.merge("RGB",tmp)
三,图像通道混合(Image)
from PIL import Image
img1 = Image.open("../input/1.png")
img2 = Image.open("../input/3.jpg")
img2 = img2.resize(img1.size)
r,g,b = img2.split()
Image.composite(img2,img1,b).show()
四,图像尺寸调整(Image)
from PIL import Image
img_resize = image.resize((200,200),Image.NEAREST)
img_resize.save("../out/更改图片大小.jpg")
img_resize2 = image.resize((int(image.width/2),int(image.height/2)),Image.NEAREST)
img_resize2.save("../out/动态更改图片大小.jpg")
suofang1_img = image.copy()
suofang1_img.thumbnail((220,100))
五,图像旋转(Image)
from PIL import Image
image = Image.open("../input/1.png")
image.rotate(60).save("../out/正旋转60度.jpg")
image.rotate(-60).save("../out/反旋转60度.jpg")
image.rotate(60,Image.NEAREST,True).save("../out/拓展图片的逆60度.jpg")
六,图像格式转换(Image)
"""
L:灰度图像--黑白,灰色
RGB:真彩色图像--屏幕显示
CMTK:出版图像--需要外界光源照射才能看的图像
"""
change_image.convert("1").save("../out/一位像素图.png",quality = 100)
change_image.convert("L").save("../out/八位灰度图.png",quality = 100)
change_image.convert("P").save("../out/八位彩图图.png",quality = 100)
"""
PIL.Image.FLIP_LEFT_RIGHT 左右镜像
PIL.Image.FLIP_TOP_BOTTOM 上下镜像
PIL.Image.ROTATE_90 旋转90
PIL.Image.ROTATE_180 旋转180
PIL.Image.ROTATE_270 旋转270
PIL.Image.TRANSPOSE 颠倒顺序
"""
image.transpose(Image.TRANSPOSE).show()
七,图像数据剪切-复制-粘贴(Image)
from PIL import Image
image = Image.open("../input/1.png")
"""
Image.crop(box = None)
box是一个四元组,代表左上右下四个坐标点
Image.paste(img,box = None,mask = None) 原图,粘贴区域,遮罩
box分为三种情况:
1.左上角对齐:(x1,y1)对齐左上角,其余部分被抛弃
2.固定粘贴区域:(x1,y1,x2,y2)
3.原图粘贴:None
"""
jianqie_img = image.copy()
zhantie_img = image.copy()
region = jianqie_img.crop((5,10,1200,1200))
zhantie_img.paste(region,(30,30))
zhantie_img.show()
八,图像滤镜效果(Image,ImageFilter)
from PIL import Image,ImageFilter
image = Image.open("../input/1.png")
w,h = image.size
img_output = Image.new("RGB",(2*w,h))
img_output.paste(image,(0,0))
filts = []
filts.append(ImageFilter.EDGE_ENHANCE)
filts.append(ImageFilter.FIND_EDGES)
filts.append(ImageFilter.GaussianBlur)
for fltr in filts:
r = image.filter(fltr)
img_output.paste(r,(w,0))
img_output.show()
九,图片通道合成(像素级)(Image,ImageChops)
from PIL import Image,ImageChops
image1 = Image.open("../input/1.png")
image2 = Image.open("../input/3.jpg")
ImageChops.add(image1,image2).show()
ImageChops.subtract(image1,image2).show()
ImageChops.darker(image1,image2).show()
ImageChops.lighter(image1,image2).show()
ImageChops.multiply(image1,image2).show()
ImageChops.screen(image1,image2).show()
ImageChops.invert(image1).show()
ImageChops.difference(image1,image2).show()
十,图片色彩,亮度,对比度,清晰度调整(Image,ImageEnhance)
from PIL import Image,ImageEnhance
image1 = Image.open("../input/1.png")
w,h = image1.size
img_out = Image.new("RGB",(5*w,h))
img_out.paste(image1,(0,0))
img_color = ImageEnhance.Color(image1)
imgb = img_color.enhance(1.5)
img_out.paste(imgb,(w,0))
img_cons = ImageEnhance.Contrast(image1)
imgc = img_cons.enhance(10)
img_out.paste(imgc,(2*w,0))
img_bri = ImageEnhance.Brightness(image1)
imgd = img_bri.enhance(2)
img_out.paste(imgd,(3*w,0))
img_sha = ImageEnhance.Sharpness(image1)
imge = img_sha.enhance(2)
img_out.paste(imge,(4*w,0))
十一,图片中二维图像绘制以及文字键入(Image,ImageDraw,ImageFont)
from PIL import Image,ImageDraw,ImageFont
image1 = Image.open("../input/1.png")
"""
绘制时需要首先创建一个画笔对象
drawObject = ImageDraw.Draw(image)
常用绘制如下:
1.绘制直线:drawObject.line([x1,y1,x2,y2],fill=None,width=0,joint=None)
fill--线条颜色 width--线条宽度 joint--线的联合类型(用时查,可以为曲线)
2.绘制圆弧:drawObject.arc([x1,y1,x2,y2],start,end,fill=None,width=0)
start--起始角度 end--终止角度
3.绘制椭圆:drawObject.ellipse([x1,y1,x2,y2],fill=None,outline=None,width=0)
outline--表示只规定圆的颜色
4.绘制弦:drawObject.chord([x1,y1,x2,y2],start,end,fill=None,outline=None,width=0)
5.绘制扇形:drawObject.pieslice([x1,y1,x2,y2],start,end,fill=None,outline=None,width=0)
6.绘制多边形:drawObject.polygon([x1,y1,x2,y2....],fill=None,outline=None)
7.绘制矩形:drawObject.rectangle([x1,y1,x2,y2],fill=None,outline=None,width=0)
8.绘制文字:drawObject.text(position,text,fill=None,font=None,anchor=None,spacing=0
,align="left",direction=None,features=None,language=None)
poistion--二元组文字位置 spacing--行之间的像素数 align--对齐方式(left,center,right)
direction--文字方向(rtl-从右到左 ltr-从左到右 ttb-从上到下)
9.绘制点:drawObject.point(xy,fill=None)
"""
image = Image.new("RGB",(300,200),"white")
drawer = ImageDraw.Draw(image)
drawer.rectangle((50,50,150,150),outline="red",fill="blue")
font = ImageFont.truetype("../input/simhei.ttf",30)
drawer.text((100,100),u"北京欢迎你",fill="green",font=font)
【应用一】制作不同透明度的图片
from PIL import Image,ImageDraw,ImageFilter
im_rgb = Image.open("../input/1.png")
im_a = Image.new("L",im_rgb.size,255)
draw = ImageDraw.Draw(im_a)
draw.rectangle((200,100,300,200),fill = 0,outline = 0 )
im_rgba = im_rgb.copy()
im_rgba.putalpha(im_a)
im_a_blur = im_a.filter(ImageFilter.GaussianBlur(10))
im_rgba.putalpha(im_a_blur)
im_rgba.save("../out/高斯羽化后且偏移的原图.png")
【应用二】特定颜色转换
from PIL import Image,ImageDraw,ImageFont,ImageFilter
image = Image.open("../input/1.png")
drawer = ImageDraw.Draw(image)
def get_color(oldcolor):
"""
黄色(255,255,0)只需要将绿色通道设置为0即可
"""
if oldcolor[0]>60 and oldcolor[1]>60:
return (oldcolor[0],0,oldcolor[2])
else:
return oldcolor
for x in range(image.width):
for y in range(image.height):
drawer.point((x,y),fill=get_color(image.getpixel((x,y))))
image.show()
【应用三】实现特定后缀文件的批处理
import os
import glob
files = glob.glob("/*.jpg")
for file in files:
img = Image.open(file)
img_resize = img.resize((int(img.width/2),int(img.height/2)))
ftitle,fext = os.path.splitext(file)
img_resize.save(ftitle + "_half" + fext)
【应用四】生成随机4字母验证码
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
width = 100
height = 100
img = Image.new("RGB",(width,height),(255,255,255))
draw = ImageDraw.Draw(img)
def get_color():
return (random.randint(200,255),random.randint(200,255),random.randint(200,255))
def get_char():
return chr(random.randint(65,90))
for x in range(width):
for y in range(height):
draw.point((x,y),fill=get_color())
font = ImageFont.truetype("../input/simhei.ttf",36)
for i in range(4):
draw.text((10+i*20,50),get_char(),font=font,fill=(255,0,0))
for i in range(2):
draw.line(((10,10),(80,80)),fill=(0,255,0),width = 3)
img.show()
【应用五】抓取全屏/指定区域 截图
from PIL import ImageGrab
img = ImageGrab.grab(bbox=(10,100,800,800))
img.save("../out/指定范围抓取.jpg")
【应用六】实现粘贴板图片数据导出
from PIL import Image, ImageGrab
im = ImageGrab.grabclipboard()
if isinstance(im, Image.Image):
print("Image: size : %s, mode: %s" % (im.size, im.mode))
im.save("grab_grabclipboard.jpg")
elif im:
for filename in im:
try:
print("filename: %s" % filename)
im = Image.open(filename)
except IOError:
pass
else:
print("ImageList: size : %s, mode: %s" % (im.size, im.mode))
else:
print("clipboard is empty.")
【应用七】实现excel中表数据转为图片并导出
import re
import win32com.client as win32
from PIL import ImageGrab,Image
import time
from ctypes import windll
def clear():
if windll.user32.OpenClipboard(None):
windll.user32.EmptyClipboard()
windll.user32.CloseClipboard()
def RGB(r,g,b):
bgr = (b, g, r)
strValue = '%02x%02x%02x' % bgr
iValue = int(strValue, 16)
return iValue
def savepic(path,sheet, data,name):
excel = win32.DispatchEx('Excel.Application')
try:
clear()
excel.Visible=False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(path)
ws = wb.WorkSheets(sheet)
print('打开excel',path)
ws.Range(data).Interior.Color = RGB(249,251,238)
ws.Range(data).ClearComments()
ws.Range(data).CopyPicture()
print('复制选择区',data)
time.sleep(1)
ws.Paste(ws.Range('A70'))
print('数据变成图片')
time.sleep(1)
pic = ws.pictures[0]
time.sleep(1)
pic.Copy()
time.sleep(1)
img = ImageGrab.grabclipboard()
if img.mode == "P":
img = img.convert('RGB')
else:
pass
img.save(name)
im = Image.open(name)
p = Image.new('RGB', im.size, (255, 255, 255))
x, y = im.size
p.paste(im, (0, 0, x, y), im)
p.save(name)
pic.Delete()
print('保存图片',name)
clear()
except:
print('图片制作失败')
finally:
wb.Save()
wb.Close()
if __name__ == '__main__':
path = 'C:/Users/Administrator/Desktop/全业务/创新/通报工作2022-4-6/source_data/model.xlsx'
sheet = '获取数据'
data = "A2:C4"
picname = 'C:/Users/Administrator/Desktop/全业务/创新/通报工作2022-4-6/temp_data/res.png'
savepic(path=path, sheet=sheet, data=data, name=picname)
|