****************************************分割线****************************************
把两张图(尺寸和模式要相同),合成为一张新图
:
from PIL import Image
backGround=Image.open('F:/666.png').convert('RGBA')
img=Image.open('F:/1.jpg').resize(backGround.size).convert('RGBA')
# backGround.paste(img,(0,40)) #按各自的尺寸合成
# backGround.show() #.save('F:/result.png')
# result=Image.blend(img,backGround,0.2) #按透明度合成
result=Image.alpha_composite(img,backGround) #背景为png透明素材
result.show()
******************分割线*******************
Egの把许多图均匀整合到一张正方形内:
import glob,random,math
from PIL import Image
def mixImages(totalSize=640):
images=glob.glob(imagesFolderPath+'\*.jpg')
totalNum=len(images)
vnum=math.ceil(math.sqrt(totalNum)) #纵向图片数:总数的方根的天花板
hnum1=math.ceil(totalNum/vnum) #除末排的横向图片数,如5、6为2,7~12为3
frontNum=hnum1*(vnum-1)
vsize=int(totalSize/vnum)
hsize1=int(totalSize/hnum1);hsize2=int(totalSize/(totalNum-frontNum))
sizes=[(hsize1,vsize) if n<frontNum else (hsize2,vsize) for n in range(totalNum)]
#4通道RGBA的png图,和3通道RGB的bmp和jpg图,都能粘贴进画布
toImage=Image.new('RGBA',(totalSize,totalSize))
x=0;y=0 #画布游标
random.shuffle(images)
for index,name in enumerate(images):
img=Image.open(name).resize(sizes[index])
toImage.paste(img,(sizes[index][0]*x,vsize*y))
x+=1
if x==hnum1:
x=0;y+=1
toImage.show()
r,g,b=toImage.split()[:3]
toImage=Image.merge('RGB',(r,g,b))
toImage.save('D:\合成图.jpg')
if __name__ == '__main__':
imagesFolderPath='D:\待整合的各图'
mixImages(totalSize=720)
******************分割线*******************
Egの分别把各图填充为正方形并均匀切为9块:
from PIL import Image
import os,pathlib
def fill(originalImage): #将原图居中贴在方形画布上
width,height=originalImage.size
newLength=max(originalImage.size)
newImage=Image.new(originalImage.mode,(newLength,newLength),color='white')
leftup=(int((newLength-width)/2),0) if width<height else (0,int((newLength-height)/2))
newImage.paste(originalImage,leftup)
newImage.save(newFilePath)
return newImage
def cut(newImage): #把方形的新图均匀切为9块
width,height=newImage.size
pieceLenth=int(width/3)
pieces=[]
for y in range(0,3):
for x in range(0,3):
piece=(x*pieceLenth,y*pieceLenth,(x+1)*pieceLenth,(y+1)*pieceLenth)
pieces.append(newImage.crop(piece))
return pieces
def save(pieces): #保存切自方形新图的9块小切图
for index,piece in enumerate(pieces):
piece.save(newFilePath.replace('_new','_'+str(index),1))
def walk(folderPath): #遍历待切的各原图
global newFilePath
filesPath=[str(path) for path in pathlib.Path(folderPath).rglob('*.jp*')]
for filePath in filesPath:
originalImage=Image.open(filePath)
newFolder=os.path.splitext(filePath)[0]
newFilePath=os.path.split(newFolder)[-1]+'_new'+os.path.splitext(filePath)[-1]
if not os.path.isdir(newFolder):
os.makedirs(newFolder)
os.chdir(newFolder)
newImage=fill(originalImage)
pieces=cut(newImage)
save(pieces)
if __name__=='__main__':
folderPath='D:\图片'
walk(folderPath)
******************分割线*******************
制作验证码:
import random,string
from PIL import Image,ImageDraw,ImageFont,ImageFilter
#每个验证码字符内又有几个字符
def rand_font(couple):
s=""
for j in range(couple):
n=random.randint(1,3) #2为数字,1&3为大小写字母
if n==2:
s+=str(random.randint(0,9))
else:
s+=random.choice(string.ascii_letters)
return s
#验证码各字符的颜色
def rand_fontColor():
return (random.randint(64,255),random.randint(64,255),random.randint(64,255))
#背景各像素的颜色
def rand_drawPixelColor():
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
#设置背景图片的宽高
width=60*4
height=60
img=Image.new('RGB',(width,height),(0,0,0)) #创建背景图片:模式、尺寸、颜色
draw=ImageDraw.Draw(img) #创建绘图对象
font=ImageFont.truetype('C:/Windows/Fonts/Arial.ttf',36) #创建字体对象
#填充背景图片每个像素点的颜色
for i in range(width):
for j in range(height):
draw.point((i,j),rand_drawPixelColor())
#写入4个验证码字符,每个字符内又含2个字符
for i in range(4):
draw.text((60*i+10,10),text=rand_font(2),fill=rand_fontColor(),font=font)
#图片加噪,增加识别难度
img=img.filter(ImageFilter.BLUR)
img.show()
******************分割线*******************
给图片配文字:
from PIL import Image,ImageDraw,ImageFont
customFont=ImageFont.truetype('F:/msyh.ttc',50)
image=Image.open('F:/原图.jpg')
width,height=image.size
draw=ImageDraw.Draw(image) #创建绘图对象
draw.text((width*1/3,height/2),'陈独秀你坐下!!','#ff0000',customFont) #图上加字
image.save('F:/新图.jpg','jpeg')
******************分割线*******************
识别图片中的文字:
tesseract-ocr.exe安装到默认路径,勾选Additional language下的Chinese(simplified)
pytesseract.py中改tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
爬到的图片b节码不存图而直接打开:Image.open(io.BytesIO(response.content)).show()
from PIL import Image
from pytesseract import image_to_string
config="--tessdata-dir 'C:/Program Files (x86)/Tesseract-OCR/tessdata'"
with Image.open('F:/New Download/1.jpg') as img:
text=image_to_string(img,'chi_sim',config=config).replace(' ','')
print(text)
******************分割线*******************
素描:
from PIL import Image
import numpy as np
a=np.asarray(Image.open('D:\原图.jpg').convert('L')).astype('float')
depth=10. # (0-100)
grad=np.gradient(a) # 取图像灰度的梯度值
grad_x,grad_y=grad # 分别取横纵图像梯度值
grad_x=grad_x*depth / 100.
grad_y=grad_y*depth / 100.
A=np.sqrt(grad_x **2+grad_y **2+1.)
uni_x=grad_x / A
uni_y=grad_y / A
uni_z=1. / A
vec_el=np.pi / 2.2 # 光源的俯视角度,弧度值
vec_az=np.pi / 4. # 光源的方位角度,弧度值
dx=np.cos(vec_el)*np.cos(vec_az) # 光源对x 轴的影响
dy=np.cos(vec_el)*np.sin(vec_az) # 光源对y 轴的影响
dz=np.sin(vec_el) # 光源对z 轴的影响
b=255*(dx*uni_x+dy*uni_y+dz*uni_z) # 光源归一化
b=b.clip(0,255)
im=Image.fromarray(b.astype('uint8')) # 重构图像
im.save('D:\素描.jpg')
******************分割线*******************
雪花飘飘:
import pygame,random
pygame.init() #初始化
size=(1364,569) #屏幕长宽同背景图
screen=pygame.display.set_mode(size)
bg=pygame.image.load('F:/New Download/snow.jpg')
pygame.display.set_caption('Snow Animation')
snows=[]
for i in range(200): #初始化雪花:[x坐标,y坐标,x轴速度,y轴速度]
x=random.randrange(0,size[0])
y=random.randrange(0,size[1])
sx=random.randint(-2,2) #.randint(3,6)=.choice(range(3,7,1))=.randrange(3,7,1)
sy=random.randint(4,7)
snows.append([x,y,sx,sy])
clock=pygame.time.Clock()
num=0
done=False
while not done:
screen.blit(bg,(0,0)) #图片背景;黑背景screen.fill((0,0,0))
for snow in snows: # 雪花列表循环
pygame.draw.circle(screen,(255,255,255),snow[:2],snow[3]-3) #画雪花:颜色,位置,大小
snow[0] +=snow[2] # 移动雪花位置(下一次循环起效)
snow[1] +=snow[3]
if snow[1] > size[1]: # 如果雪花落出屏幕,重设位置
snow[1]=random.randrange(-50,-10)
snow[0]=random.randrange(0,size[0])
pygame.display.flip() # 刷新屏幕
clock.tick(20)
num+=1
if num<5:
pygame.image.save(screen,f'F:/New Download/snow-{num}.jpg')
for event in pygame.event.get():
if event.type==pygame.QUIT:
done=True
pygame.quit()