五个有趣的Python练手小项目,附代码

 

Python不仅相对其他编程语言来说容易上手,在生活中,可能Python的技术范围程度没有其他编程语言深,但Python 绝对是最接地气的,论起来,Python亲民度也可以说是老大哥的位置了。那么Python在我们生活中有哪些有趣的小功能可以运用呢?

 

一、词云图

 

 

你是不是经常能在网络上看到这种图片,其实这种图片的官方名字叫词云图。“词云”的概念最早是美国西北大学新闻学副教授、新媒体专业主任里奇•戈登(Rich Gordon)提出的。词云(Word Cloud),是文本数据的一种可视化展现方式,它一般是由文本数据中提取的词汇组成某些彩色图形。词云图的核心在于以高频关键词的可视化表达来传达大量文本数据背后的有价值的信息,这也是利用Python完成的。

 

词云代码:

def wordCloudImage(wordlist,width,height,bgcolor,savepath):

# 可以打开你喜欢的词云展现背景图

# cloud_mask = np.array(Image.open('nezha.png'))

# 定义词云的一些属性

wc = WordCloud(

width=width, # 图幅宽度 900

height=height, # 图幅高度 3000

background_color=bgcolor, # 背景图分割颜色为白色 "black"

# mask=cloud_mask, # 背景图样

max_words=300, # 显示最大词数

font_path='./fonts/simhei.ttf', # 显示中文

collocations=False,

# min_font_size=5, # 最小尺寸

# max_font_size=100, # 最大尺寸

)

# wordfile是分词后的词汇列表

x = wc.generate(wordlist)

# 生成词云图片

image = x.to_image()

# 展示词云图片

image.show()

# savepath是图片保存地址,保存词云图片

wc.to_file(savepath)

 

二、生成手绘投票

 

现在很多软件都可以实现将照片转换成手绘形式的技术,但是有些软件会收费,在这里,我们用python也可以实现,用Python处理的优点在于个性更强,可定制化;并且可以实现批量转换,方便快捷。

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

 

原图:

 

手绘图:

 

代码:

# -*- coding: UTF-8 -*-

from PIL import Image

import numpy as np

# 原始图片路径

original_image_path = "E:\\图片\\陆家嘴.jpg"

# 要生成的手绘图片路径,可自定义

handdrawn_image_path = "E:\\图片\\陆家嘴-手绘.jpg"

# 加载原图,将图像转化为数组数据

a=np.asarray(Image.open(original_image_path).convert('L')).astype('float')

depth=10.

#取图像灰度的梯度值

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.

#光源对x轴的影响

dx=np.cos(vec_el)*np.cos(vec_az)

dy=np.cos(vec_el)*np.sin(vec_az)

dz=np.sin(vec_el)

#光源归一化,把梯度转化为灰度

b=255*(dx*uni_x+dy*uni_y+dz*uni_z)

#避免数据越界,将生成的灰度值裁剪至0-255内

b=b.clip(0,255)

#图像重构

im=Image.fromarray(b.astype('uint8'))

print('完成')

im.save(handdrawn_image_path)

 

三、生成艺术二维码

 

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

 

代码:

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

 

四、生成证件照

 

这里用到pillowremovebg两组代码,分别用于修改照片尺寸和抠图。

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

 

 

代码:

# encoding=utf-8

from PIL import Image

from removebg import RemoveBg

# removebg涉及到api_key,需要到其官网申请

api_key = 'PysKLJueeoyK9NbJXXXXXXXXX'

def change_bgcolor(file_in, file_out, api_key, color):

'''

#必须为png格式

'''

p, s = file_in.split(".")

rmbg = RemoveBg(api_key, 'error.log')

rmbg.remove_background_from_img_file(file_in)

file_no_bg = "{}.{}_no_bg.{}".format(p, s, s)

no_bg_image = Image.open(file_no_bg)

x, y = no_bg_image.size

new_image = Image.new('RGBA', no_bg_image.size, color=color)

new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)

new_image.save(file_out)

# 修改照片尺寸

def change_size(file_in, file_out, width, height):

image = Image.open(file_in)

resized_image = image.resize((width, height), Image.ANTIALIAS)

resized_image.save(file_out)

if __name__ == "__main__":

file_in = 'E:\\girl.png'

file_out = 'E:\\girl_cutout.png'

# 尺寸可按需求自修改

# change_size(file_in, file_out, width, height)



# 换背景色

color = (0, 125, 255)

change_bgcolor(file_in, file_out, api_key, color)

 

五、生成九宫格图片

 

有段时间朋友圈比较流行九宫格图片,就是一张图分割成九张图, 迅速在朋友圈脱颖而出,看起来特别文艺、特别高级。这个九宫格也可以用很多软件来做,如果使用Python去实现,只需要不到50行的代码就可以稿定了。

 

代码:

# 朋友圈九宫格图片制作

# encoding=utf-8

from PIL import Image

import sys

# 先将input image 填充为正方形

def fill_image(image):

width, height = image.size

# 选取原图片长、宽中较大值作为新图片的九宫格半径

new_image_length = width if width > height else height

# 生产新图片【白底】

new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')

# 将原图粘贴在新图上,位置为居中

if width > height:

new_image.paste(image, (0, int((new_image_length - height) / 2)))

else:

new_image.paste(image, (int((new_image_length - width) / 2), 0))

return new_image

# 将图片切割成九宫格

def cut_image(image):

width, height = image.size

# 一行放3张图

item_width = int(width / 3)

box_list = []

for i in range(0, 3):

for j in range(0, 3):

box = (j * item_width, i * item_width, (j + 1) * item_width, (i + 1) * item_width)

box_list.append(box)

image_list = [image.crop(box) for box in box_list]

return image_list

# 保存图片

def save_images(image_list):

index = 1

for image in image_list:

image.save('e:\\图片\\'+str(index) + '.png', 'PNG')

index += 1

if __name__ == '__main__':

file_path = "e:\\图片\\龙猫.jpg"

image = Image.open(file_path)

# image.show()

image = fill_image(image)

image_list = cut_image(image)

print(len(image_list))

save_images(image_list)

 

在这里还是要推荐下我自己建的Python学习Q群:249029188,群里都是学Python的,如果你想学或者正在学习Python ,欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2021最新的Python进阶资料和零基础教学,欢迎进阶中和对Python感兴趣的小伙伴加入!

  • 11
    点赞
  • 131
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值