脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python处理图像五个有趣场景,很实用!

Python处理图像五个有趣场景,很实用!

2021-03-29 23:12Python大数据分析有派君 Python

Python像是叮当猫的口袋,几乎什么都能做,适合外行小白们去摸索学习,能极大的增加对编程的兴趣。

有些工具用python来实现不一定是技术上的最优选择,但可能是最简洁、最面向大众的。

介绍几个不错的处理图像的案例,并附上代码,尽可能让大家能拿来就用。

1、生成手绘图片

 

现在很多软件可以将照片转换成手绘形式,python也可以实现,而且定制化更强,可批量转换。

这里用到pillow库,这是非常牛逼且专业的Python图像处理

原图:

Python处理图像五个有趣场景,很实用!

生成手绘后:

Python处理图像五个有趣场景,很实用!

代码:

  1. # -*- coding: UTF-8 -*- 
  2. from PIL import Image 
  3. import numpy as np 
  4.  
  5. # 原始图片路径 
  6. original_image_path = "E:\\图片\\陆家嘴.jpg" 
  7. # 要生成的手绘图片路径,可自定义 
  8. handdrawn_image_path = "E:\\图片\\陆家嘴-手绘.jpg" 
  9.  
  10. # 加载原图,将图像转化为数组数据 
  11. a=np.asarray(Image.open(original_image_path).convert('L')).astype('float'
  12. depth=10. 
  13.  
  14. #取图像灰度的梯度值 
  15. grad=np.gradient(a) 
  16.  
  17. #取横纵图像梯度值 
  18. grad_x,grad_y=grad 
  19. grad_x=grad_x*depth/100. 
  20. grad_y=grad_y*depth/100. 
  21. A=np.sqrt(grad_x**2+grad_y**2+1.) 
  22. uni_x=grad_x/A 
  23. uni_y=grad_y/A 
  24. uni_z=1./A 
  25.  
  26. #光源的俯视角度转化为弧度值 
  27. vec_el=np.pi/2.2 
  28.  
  29. #光源的方位角度转化为弧度值 
  30. vec_az=np.pi/4. 
  31.  
  32. #光源对x轴的影响 
  33. dx=np.cos(vec_el)*np.cos(vec_az) 
  34. dy=np.cos(vec_el)*np.sin(vec_az) 
  35. dz=np.sin(vec_el) 
  36.  
  37. #光源归一化,把梯度转化为灰度 
  38. b=255*(dx*uni_x+dy*uni_y+dz*uni_z) 
  39.  
  40. #避免数据越界,将生成的灰度值裁剪至0-255内 
  41. b=b.clip(0,255) 
  42.  
  43. #图像重构 
  44. im=Image.fromarray(b.astype('uint8')) 
  45.  
  46. print('完成'
  47. im.save(handdrawn_image_path) 

这里可以做成批量处理的转手绘脚本,大家试试。

2、生成证件照

 

这里用到pillow和removebg,分别用于修改照片尺寸和抠图。

这里removebg用到了AI技术,抠图边缘很柔和,效果挺不错的。

Python处理图像五个有趣场景,很实用!

代码:

  1. # encoding=utf-8 
  2. from PIL import Image 
  3. from removebg import RemoveBg 
  4.  
  5. # removebg涉及到api_key,需要到其官网申请 
  6. api_key = 'PysKLJueeoyK9NbJXXXXXXXXX' 
  7.  
  8. def change_bgcolor(file_in, file_out, api_key, color): 
  9.   ''
  10.       #必须为png格式 
  11.   ''
  12.   p, s = file_in.split("."
  13.   rmbg = RemoveBg(api_key, 'error.log'
  14.   rmbg.remove_background_from_img_file(file_in) 
  15.   file_no_bg = "{}.{}_no_bg.{}".format(p, s, s) 
  16.   no_bg_image = Image.open(file_no_bg) 
  17.   x, y = no_bg_image.size 
  18.   new_image = Image.new('RGBA', no_bg_image.size, color=color) 
  19.   new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image) 
  20.   new_image.save(file_out) 
  21.  
  22.  
  23. # 修改照片尺寸 
  24. def change_size(file_in, file_out, width, height): 
  25.   image = Image.open(file_in) 
  26.   resized_image = image.resize((width, height), Image.ANTIALIAS) 
  27.   resized_image.save(file_out) 
  28.  
  29.  
  30. if __name__ == "__main__"
  31.   file_in = 'E:\\girl.png' 
  32.   file_out = 'E:\\girl_cutout.png' 
  33.   # 尺寸可按需求自修改 
  34.   # change_size(file_in, file_out, width, height) 
  35.    
  36.   # 换背景色 
  37.   color = (0, 125, 255) 
  38.   change_bgcolor(file_in, file_out, api_key, color) 
  39.    

3、生成艺术二维码

 

现在有不少二维码生成工具,python也有一款二维码生成库-myqr,可以给二维码加上图片背景,看起来很炫,效果如下

Python处理图像五个有趣场景,很实用!

使用pip安装myqr,非常简单。

该库可以在命令行中运行,你只需要传递网址链接、图片地址等参数,就可以生成相应的二维码,二维码图片默认保存在当前目录下面。

命令行输入格式:

myqr 网址链接

比如:

  1. myqr https://zhuanlan.zhihu.com/pydatalysis 

再按enter键执行,就能生成对应链接的二维码了。

怎么融合图片呢?很简单,传入图片地址参数'-p'

比如说我d盘有一张海绵宝宝的图片,地址是:d:\hmbb.jpg即传入参数'-pd:\hmbb.jpg'在命令行键入:

  1. myqr https://zhuanlan.zhihu.com/pydatalysis -p d:\hmbb.jpg -c 

执行就能生成上图的海绵宝宝主题二维码了。

4、生成词云图

 

词云图一般用来凸显文本关键词,产生视觉上的焦点,利用好词云会让数据更加有说服力。

python也有专门制作词云的库-wordcloud,能自定义颜色和形状。

比如我用小丑的豆瓣评论做成一张词云图。

Python处理图像五个有趣场景,很实用!

作词云图,首先要对收集文本,然后对文本做分词处理,最后生成词云。

这里不对前两步做详细解析,只给出词云代码:

  1. def wordCloudImage(wordlist,width,height,bgcolor,savepath): 
  2.     # 可以打开你喜欢的词云展现背景图 
  3.     # cloud_mask = np.array(Image.open('nezha.png')) 
  4.     # 定义词云的一些属性 
  5.     wc = WordCloud( 
  6.         width=width,  # 图幅宽度 900 
  7.         height=height,  # 图幅高度 3000 
  8.         background_color=bgcolor,  # 背景图分割颜色为白色 "black" 
  9.         # mask=cloud_mask,  # 背景图样 
  10.         max_words=300,  # 显示最大词数 
  11.         font_path='./fonts/simhei.ttf',  # 显示中文 
  12.         collocations=False
  13.         # min_font_size=5,  # 最小尺寸 
  14.         # max_font_size=100,  # 最大尺寸 
  15.     ) 
  16.  
  17.     # wordfile是分词后的词汇列表 
  18.     x = wc.generate(wordlist) 
  19.     # 生成词云图片 
  20.     image = x.to_image() 
  21.     # 展示词云图片 
  22.     image.show() 
  23.     # savepath是图片保存地址,保存词云图片 
  24.     wc.to_file(savepath) 

5、生成微信九宫格图片

 

有段时间朋友圈比较流行九宫格图片,就是一张图分割成九张图,看着似乎很文艺。

这个可以用很多软件来做,python当然也能实现,只需不到50行代码。

Python处理图像五个有趣场景,很实用!

代码:

  1. # 朋友圈九宫格图片制作 
  2. # encoding=utf-8 
  3. from PIL import Image 
  4. import sys 
  5.  
  6.  
  7. # 先将input image 填充为正方形 
  8. def fill_image(image): 
  9.     width, height = image.size 
  10.     # 选取原图片长、宽中较大值作为新图片的九宫格半径 
  11.     new_image_length = width if width > height else height 
  12.     # 生产新图片【白底】 
  13.     new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white'
  14.     # 将原图粘贴在新图上,位置为居中 
  15.     if width > height: 
  16.         new_image.paste(image, (0, int((new_image_length - height) / 2))) 
  17.     else
  18.         new_image.paste(image, (int((new_image_length - width) / 2), 0)) 
  19.     return new_image 
  20.  
  21.  
  22. # 将图片切割成九宫格 
  23. def cut_image(image): 
  24.     width, height = image.size 
  25.     # 一行放3张图 
  26.     item_width = int(width / 3) 
  27.     box_list = [] 
  28.     for i in range(0, 3): 
  29.         for j in range(0, 3): 
  30.             box = (j * item_width, i * item_width, (j + 1) * item_width, (i + 1) * item_width) 
  31.             box_list.append(box) 
  32.     image_list = [image.crop(box) for box in box_list] 
  33.     return image_list 
  34.  
  35.  
  36. # 保存图片 
  37. def save_images(image_list): 
  38.     index = 1 
  39.     for image in image_list: 
  40.         image.save('e:\\图片\\'+str(index) + '.png', 'PNG') 
  41.         index += 1 
  42.  
  43.  
  44. if __name__ == '__main__'
  45.     file_path = "e:\\图片\\龙猫.jpg" 
  46.     image = Image.open(file_path) 
  47.     # image.show() 
  48.     image = fill_image(image) 
  49.     image_list = cut_image(image) 
  50.     print(len(image_list)) 
  51.     save_images(image_list) 

python还可以做很多有趣的图像处理,大家可以玩起来!

原文地址:https://mp.weixin.qq.com/s?__biz=MzA3ODYwNDkzOQ==&mid=2659064501&idx=1&sn=b05192fed02526f2626edc7585eecb50&chksm=84ca8551b3bd0c477d9d004340e3b095111fe20174ab4e377a452c0f58cac19b256c2b01716e&mpshare=1&

延伸 · 阅读

精彩推荐