作为程序员,这些年给女神写了无数的表白代码。这里简单分享一部分,希望对您有所帮助,520哈哈~
文章目录:
每次我上《Python数据挖掘》或《大数据分析》课程时,都会给学生普及一句话表白代码,这是非常简单有趣的代码。
print('\n'.join([''.join([('loveNana'[(x-y)%8]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15,-15,-1)]))
运行结果如下图所示,输出“lovaNana”的桃心。
同样可以调用笛卡尔函数绘制桃心,这也是我课堂布置的某个作业。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-8 , 8, 1024)
y1 = 0.618*np.abs(x) - 0.8* np.sqrt(64-x**2) #左部分
y2 = 0.618*np.abs(x) + 0.8* np.sqrt(64-x**2) #右部分
plt.plot(x, y1, color = 'r')
plt.plot(x, y2, color = 'r')
plt.show()
如果你觉得上面的代码颜色不够喜庆,接下来我们调用turtle库绘制动态红色的桃心。
from turtle import *
#初始设置
setup(750,500)
penup()
pensize(25)
pencolor("pink")
fd(-230)
seth(90)
pendown()
#绘制桃心
circle(-50,180)
circle(50,-180)
circle(75,-50)
circle(-190,-45)
penup()
fd(185)
seth(180)
fd(120)
seth(90)
pendown()
circle(-75,-50)
circle(190,-45)
penup()
fd(184)
seth(0)
fd(80)
seth(90)
pendown()
circle(-50,180)
circle(50,-180)
circle(75,-50)
circle(-190,-45)
penup()
fd(185)
seth(180)
fd(120)
seth(90)
pendown()
circle(-75,-50)
circle(190,-45)
penup()
fd(150)
seth(180)
fd(300)
#绘制箭头
pencolor("red")
pensize(10)
pendown()
fd(-500)
seth(90)
fd(30)
fd(-60)
seth(30)
fd(60)
seth(150)
fd(60)
done()
运行效果如下图所示:
如果你觉得上面的代码颜色不够喜庆,接下来我们调用turtle库绘制动态红色的桃心。
如果还是觉得桃心单调,我们可以绘制3D桃心,主要调用Axes3D和Matplotlib包实现。代码如下:
#coding:utf-8
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
#绘制3D桃心
def heart_3d(x,y,z):
return (x**2+(9/4)*y**2+z**2-1)**3-x**2*z**3-(9/80)*y**2*z**3
#图像展示
def plot_implicit(fn, bbox=(-1.5, 1.5)):
xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
A = np.linspace(xmin, xmax, 100) #resolution of the contour
B = np.linspace(xmin, xmax, 40) #number of slices
A1, A2 = np.meshgrid(A, A) #grid on which the contour is plotted
#plot contours in the XY plane
for z in B:
X, Y = A1, A2
Z = fn(X, Y, z)
cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))
# [z] defines the only level to plot
# for this contour for this value of z
#plot contours in the XZ plane
for y in B:
X, Z = A1, A2
Y = fn(X, y, Z)
cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))
#plot contours in the YZ plane
for x in B:
Y, Z = A1, A2
X = fn(x, Y, Z)
cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))
#轴
ax.set_zlim3d(zmin, zmax)
ax.set_xlim3d(xmin, xmax)
ax.set_ylim3d(ymin, ymax)
#显示图像
plt.show()
#主函数
if __name__ == '__main__':
plot_implicit(heart_3d)
输出结果如下图所示:
“词云”就是对网络文本中出现频率较高的关键词,予以视觉上的突出,使浏览网页者只要一眼扫过文本就可以领略文本的主旨,主要利用文本挖掘和可视化技术。
作者将两人的微信聊天记录导出,利用下面的代码绘制属于两人的词云图,其中“宝宝”、“我们”、“哈哈”最多。如果增加停用词过滤,可以看到属于你们的故事喔~
# -*- coding: utf-8 -*-
from os import path
from scipy.misc import imread
import jieba
import sys
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
# 打开本体TXT文件
text = open('test.txt').read()
# 结巴分词 cut_all=True 设置为全模式
wordlist = jieba.cut(text) #cut_all = True
# 使用空格连接 进行中文分词
wl_space_split = " ".join(wordlist)
print(wl_space_split)
# 读取mask/color图片
d = path.dirname(__file__)
nana_coloring = imread(path.join(d, "mb.png"))
# 对分词后的文本生成词云
my_wordcloud = WordCloud( background_color = 'white',
mask = nana_coloring,
max_words = 2000,
stopwords = STOPWORDS,
max_font_size = 50,
random_state = 30,
)
# generate word cloud
my_wordcloud.generate(wl_space_split)
# create coloring from image
image_colors = ImageColorGenerator(nana_coloring)
# recolor wordcloud and show
my_wordcloud.recolor(color_func=image_colors)
plt.imshow(my_wordcloud) # 显示词云图
plt.axis("off") # 是否显示x轴、y轴下标
plt.show()
# save img
my_wordcloud.to_file(path.join(d, "cloudimg.png"))
作者之前分享了图像处理,同样我们可以用Python制作各种图像处理,为女神量身定义一个PS工具。这里分享相关代码:
#encoding:utf-8
#By:Eastmount CSDN 2021-02-06
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import math
#读取图片
img = cv2.imread('na.png')
src = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#新建目标图像
dst1 = np.zeros_like(img)
#获取图像行和列
rows, cols = img.shape[:2]
#--------------------------------毛玻璃效果-----------------------------------
#像素点邻域内随机像素点的颜色替代当前像素点的颜色
offsets = 5
random_num = 0
for y in range(rows - offsets):
for x in range(cols - offsets):
random_num = np.random.randint(0,offsets)
dst1[y,x] = src[y + random_num,x + random_num]
#--------------------------------油漆特效-------------------------------------
#图像灰度处理
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#自定义卷积核
kernel = np.array([[-1,-1,-1],[-1,10,-1],[-1,-1,-1]])
#图像浮雕效果
dst2 = cv2.filter2D(gray, -1, kernel)
#--------------------------------素描特效-------------------------------------
#高斯滤波降噪
gaussian = cv2.GaussianBlur(gray, (5,5), 0)
#Canny算子
canny = cv2.Canny(gaussian, 50, 150)
#阈值化处理
ret, dst3 = cv2.threshold(canny, 100, 255, cv2.THRESH_BINARY_INV)
#--------------------------------怀旧特效-------------------------------------
#新建目标图像
dst4 = np.zeros((rows, cols, 3), dtype="uint8")
#图像怀旧特效
for i in range(rows):
for j in range(cols):
B = 0.272*img[i,j][2] + 0.534*img[i,j][1] + 0.131*img[i,j][0]
G = 0.349*img[i,j][2] + 0.686*img[i,j][1] + 0.168*img[i,j][0]
R = 0.393*img[i,j][2] + 0.769*img[i,j][1] + 0.189*img[i,j][0]
if B>255:
B = 255
if G>255:
G = 255
if R>255:
R = 255
dst4[i,j] = np.uint8((B, G, R))
#--------------------------------光照特效-------------------------------------
#设置中心点
centerX = rows / 2
centerY = cols / 2
print(centerX, centerY)
radius = min(centerX, centerY)
print(radius)
#设置光照强度
strength = 200
#新建目标图像
dst5 = np.zeros((rows, cols, 3), dtype="uint8")
#图像光照特效
for i in range(rows):
for j in range(cols):
#计算当前点到光照中心的距离(平面坐标系中两点之间的距离)
distance = math.pow((centerY-j), 2) + math.pow((centerX-i), 2)
#获取原始图像
B = src[i,j][0]
G = src[i,j][1]
R = src[i,j][2]
if (distance < radius * radius):
#按照距离大小计算增强的光照值
result = (int)(strength*( 1.0 - math.sqrt(distance) / radius ))
B = src[i,j][0] + result
G = src[i,j][1] + result
R = src[i,j][2] + result
#判断边界 防止越界
B = min(255, max(0, B))
G = min(255, max(0, G))
R = min(255, max(0, R))
dst5[i,j] = np.uint8((B, G, R))
else:
dst5[i,j] = np.uint8((B, G, R))
#--------------------------------怀旧特效-------------------------------------
#新建目标图像
dst6 = np.zeros((rows, cols, 3), dtype="uint8")
#图像流年特效
for i in range(rows):
for j in range(cols):
#B通道的数值开平方乘以参数12
B = math.sqrt(src[i,j][0]) * 12
G = src[i,j][1]
R = src[i,j][2]
if B>255:
B = 255
dst6[i,j] = np.uint8((B, G, R))
#--------------------------------卡通特效-------------------------------------
#定义双边滤波的数目
num_bilateral = 7
#用高斯金字塔降低取样
img_color = src
#双边滤波处理
for i in range(num_bilateral):
img_color = cv2.bilateralFilter(img_color, d=9, sigmaColor=9, sigmaSpace=7)
#灰度图像转换
img_gray = cv2.cvtColor(src, cv2.COLOR_RGB2GRAY)
#中值滤波处理
img_blur = cv2.medianBlur(img_gray, 7)
#边缘检测及自适应阈值化处理
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
blockSize=9,
C=2)
#转换回彩色图像
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
#与运算
dst6 = cv2.bitwise_and(img_color, img_edge)
#--------------------------------均衡化特效-------------------------------------
#新建目标图像
dst7 = np.zeros((rows, cols, 3), dtype="uint8")
#提取三个颜色通道
(b, g, r) = cv2.split(src)
#彩色图像均衡化
bH = cv2.equalizeHist(b)
gH = cv2.equalizeHist(g)
rH = cv2.equalizeHist(r)
#合并通道
dst7 = cv2.merge((bH, gH, rH))
#--------------------------------边缘特效-------------------------------------
#高斯滤波降噪
gaussian = cv2.GaussianBlur(gray, (3,3), 0)
#Canny算子
#dst8 = cv2.Canny(gaussian, 50, 150)
# Scharr算子
x = cv2.Scharr(gaussian, cv2.CV_32F, 1, 0) #X方向
y = cv2.Scharr(gaussian, cv2.CV_32F, 0, 1) #Y方向
absX = cv2.convertScaleAbs(x)
absY = cv2.convertScaleAbs(y)
dst8 = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
#-----------------------------------------------------------------------------
#用来正常显示中文标签
plt.rcParams['font.sans-serif']=['SimHei']
#循环显示图形
titles = [ '原图', '毛玻璃', '浮雕', '素描', '怀旧', '光照', '卡通', '均衡化', '边缘']
images = [src, dst1, dst2, dst3, dst4, dst5, dst6, dst7, dst8]
for i in range(9):
plt.subplot(3, 3, i+1), plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
输出结果如下图所示,包括毛玻璃、油漆、素描、怀旧、光照、卡通、均衡化、边缘特效。
素描和滤镜是非常棒的两个效果,我们同样可以用Python代码实现。
#coding:utf-8
import cv2
import numpy as np
def dodgeNaive(image, mask):
# determine the shape of the input image
width, height = image.shape[:2]
# prepare output argument with same size as image
blend = np.zeros((width, height), np.uint8)
for col in range(width):
for row in range(height):
# do for every pixel
if mask[col, row] == 255:
# avoid division by zero
blend[col, row] = 255
else:
# shift image pixel value by 8 bits
# divide by the inverse of the mask
tmp = (image[col, row] << 8) / (255 - mask)
# print('tmp={}'.format(tmp.shape))
# make sure resulting value stays within bounds
if tmp.any() > 255:
tmp = 255
blend[col, row] = tmp
return blend
def dodgeV2(image, mask):
return cv2.divide(image, 255 - mask, scale=256)
def burnV2(image, mask):
return 255 - cv2.divide(255 - image, 255 - mask, scale=256)
def rgb_to_sketch(src_image_name, dst_image_name):
img_rgb = cv2.imread(src_image_name)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# 读取图片时直接转换操作
# img_gray = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)
img_gray_inv = 255 - img_gray
img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(21, 21),
sigmaX=0, sigmaY=0)
img_blend = dodgeV2(img_gray, img_blur)
cv2.imshow('original', img_rgb)
cv2.imshow('gray', img_gray)
cv2.imshow('gray_inv', img_gray_inv)
cv2.imshow('gray_blur', img_blur)
cv2.imshow("pencil sketch", img_blend)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite(dst_image_name, img_blend)
if __name__ == '__main__':
src_image_name = 'nv.png'
dst_image_name = 'sketch_example.jpg'
rgb_to_sketch(src_image_name, dst_image_name)
运行结果如下图所示,我们可以根据素描绘制手札,这些年我也为女神画了好几本,哈哈。
同样,通过下面的滤镜模板我们能让图片的色彩更加饱和。
#coding:utf-8
#By:Eastmount CSDN 2020-12-22
import cv2
import math
import numpy as np
#读取原始图像
img = cv2.imread('nv.png')
#获取图像行和列
rows, cols = img.shape[:2]
#新建目标图像
dst = np.zeros((rows, cols, 3), dtype="uint8")
#图像流年特效
for i in range(rows):
for j in range(cols):
#B通道的数值开平方乘以参数12
B = math.sqrt(img[i,j][0]) * 12
G = img[i,j][1]
R = img[i,j][2]
if B>255:
B = 255
dst[i,j] = np.uint8((B, G, R))
#显示图像
cv2.imshow('src', img)
cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()
输出结果如下图所示:
代码如下:
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 23 12:45:47 2016
@author: yxz15
"""
from PIL import Image
import os
serarr=['@','#','$','%','&','?','*','o','/','{','[','(','|','!','^','~','-','_',':',';',',','.','`',' ']
count=len(serarr)
def toText(image_file):
image_file=image_file.convert("L")#转灰度
asd =''#储存字符串
for h in range(0, image_file.size[1]):#h
for w in range(0, image_file.size[0]):#w
gray =image_file.getpixel((w,h))
asd=asd+serarr[int(gray/(255/(count-1)))]
asd=asd+'\r\n'
return asd
def toText2(image_file):
asd =''#储存字符串
for h in range(0, image_file.size[1]):#h
for w in range(0, image_file.size[0]):#w
r,g,b =image_file.getpixel((w,h))
gray =int(r* 0.299+g* 0.587+b* 0.114)
asd=asd+serarr[int(gray/(255/(count-1)))]
asd=asd+'\r\n'
return asd
image_file = Image.open("nana.jpg") # 打开图片
image_file=image_file.resize((int(image_file.size[0]*0.9), int(image_file.size[1]*0.5)))#调整图片大小
print('Info:',image_file.size[0],' ',image_file.size[1],' ',count)
try:
os.remove('./tmp.txt')
except WindowsError:
pass
tmp=open('tmp.txt','a')
tmp.write(toText2(image_file))
tmp.close()
输出结果如下图所示,放我的傻照。
基本流程如下:
model.predict_output_word(poem[-self.window:],
max(self.topn, len(poem) + 1))
运行结果如下图所示:
比如输入女神的姓“颜”,输出的五言绝句、七严绝句如下所示,注意“病眉鬓凋跎”在我们的“古诗词.txt”中是找不到的,而是因为“凋”和“娜”存在相似度语义所致。同时,某些文字可能不存在,需要我们丰富文本库。
输入标题:颜
《颜跎悴憔》
病眉鬓凋跎,毛壮衰悴憔。筋齿斑肌霜,茎枯瘦健肤。
《颜跎徂逾》
壮憔跎惨蹉冉岁,凋悴辛质鬓弱衰。霰羸齿改加霜瘦,发病苦劲筋热饥。
《颜跎蹉叹》
叹跎悲哉矣悴壮嗟辛,涕鬓凋衰蹉伤齿血毛。
完整代码如下:
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 23 17:48:50 2019
@author: xiuzhang Eastmount CSDN
博客原地址:https://blog.csdn.net/Yellow_python/article/details/86726619
推荐大家学习Yellow_python大神的文章
"""
from gensim.models import Word2Vec # 词向量
from random import choice
from os.path import exists
class CONF:
path = '古诗词.txt'
window = 16 # 滑窗大小
min_count = 60 # 过滤低频字
size = 125 # 词向量维度
topn = 14 # 生成诗词的开放度
model_path = 'word2vec'
# 定义模型
class Model:
def __init__(self, window, topn, model):
self.window = window
self.topn = topn
self.model = model # 词向量模型
self.chr_dict = model.wv.index2word # 字典
"""模型初始化"""
@classmethod
def initialize(cls, config):
if exists(config.model_path):
# 模型读取
model = Word2Vec.load(config.model_path)
else:
# 语料读取
with open(config.path, encoding='utf-8') as f:
ls_of_ls_of_c = [list(line.strip()) for line in f]
# 模型训练和保存
model = Word2Vec(sentences=ls_of_ls_of_c, size=config.size, window=config.window, min_count=config.min_count)
model.save(config.model_path)
return cls(config.window, config.topn, model)
"""古诗词生成"""
def poem_generator(self, title, form):
filter = lambda lst: [t[0] for t in lst if t[0] not in [',', '。']]
# 标题补全
if len(title) < 4:
if not title:
title += choice(self.chr_dict)
for _ in range(4 - len(title)):
similar_chr = self.model.similar_by_word(title[-1], self.topn // 2)
similar_chr = filter(similar_chr)
char = choice([c for c in similar_chr if c not in title])
title += char
# 文本生成
poem = list(title)
for i in range(form[0]):
for _ in range(form[1]):
predict_chr = self.model.predict_output_word(poem[-self.window:], max(self.topn, len(poem) + 1))
predict_chr = filter(predict_chr)
char = choice([c for c in predict_chr if c not in poem[len(title):]])
poem.append(char)
poem.append(',' if i % 2 == 0 else '。')
length = form[0] * (form[1] + 1)
return '《%s》' % ''.join(poem[:-length]) + '\n' + ''.join(poem[-length:])
def main(config=CONF):
form = {'五言绝句': (4, 5), '七言绝句': (4, 7), '对联': (2, 9)}
m = Model.initialize(config)
while True:
title = input('输入标题:').strip()
try:
poem = m.poem_generator(title, form['五言绝句'])
print('%s' % poem) # red
poem = m.poem_generator(title, form['七言绝句'])
print('%s' % poem) # yellow
poem = m.poem_generator(title, form['对联'])
print('%s' % poem) # purple
print()
except:
pass
if __name__ == '__main__':
main()
PS:该部分参考了Yellow_python大神的博客,推荐人工智能的童鞋去学习他的文章,真心不错。
除了Python,各种编程语言都能制作精美的表白代码,下面补充HTML5的代码供大家学习。当然,网上开源的也非常多,本文所有代码可以在下面的链接下载。