如何预测你和心仪的Ta有没有夫妻相?
基于华为云ModelArts开发的【一键预测你和Ta的CP值】Demo帮你预测CP指数。
该模型利用ssim算法综合计算五官特征相似程度,从而得出CP值。
//夫妻相的原理在当今心理学、生物学仍有很大争议,夫妻相指数高并不意味着两人未来一定会幸福美满,也不能预判彼此关系变好变坏。本案例只适用于AI技术的学习以及情人节娱乐。
1.下载需要的海报文件和字体
import os
import os.path as osp
import moxing as mox
parent = osp.join(os.getcwd(),'Valentine')
if not os.path.exists(parent):
mox.file.copy_parallel('obs://modelarts-labs-bj4-v2/case_zoo/Valentine',parent)
if os.path.exists(parent):
print('Download success')
else:
raise Exception('Download Failed')
else:
print("Model Package already exists!")
2.使用ssim算法计算夫妻相
import numpy as np
import cv2
import random
import matplotlib.pyplot as plt
from matplotlib import font_manager
import warnings
from scipy.signal import convolve2d
from PIL import Image,ImageDraw,ImageFont
warnings.filterwarnings('ignore')
def matlab_style_gauss2D(shape=(3,3),sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's
fspecial('gaussian',[shape],[sigma])
"""
m,n = [(ss-1.)/2. for ss in shape]
y,x = np.ogrid[-m:m+1,-n:n+1]
h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )
h[ h < np.finfo(h.dtype).eps*h.max() ] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
return h
def filter2(x, kernel, mode='same'):
return convolve2d(x, np.rot90(kernel, 2), mode=mode)
def compute_ssim(im1, im2, k1=0.01, k2=0.04, win_size=11, L=255):
if not im1.shape == im2.shape:
raise ValueError("Input Imagees must have the same dimensions")
if len(im1.shape) > 2:
raise ValueError("Please input the images with 1 channel")
M, N = im1.shape
C1 = (k1*L)**2
C2 = (k2*L)**2
window = matlab_style_gauss2D(shape=(win_size,win_size), sigma=0.5)
window = window/np.sum(np.sum(window))
if im1.dtype == np.uint8:
im1 = np.double(im1)
if im2.dtype == np.uint8:
im2 = np.double(im2)
mu1 = filter2(im1, window, 'valid')
mu2 = filter2(im2, window, 'valid')
mu1_sq = mu1 * mu1
mu2_sq = mu2 * mu2
mu1_mu2 = mu1 * mu2
sigma1_sq = filter2(im1*im1, window, 'valid') - mu1_sq
sigma2_sq = filter2(im2*im2, window, 'valid') - mu2_sq
sigmal2 = filter2(im1*im2, window, 'valid') - mu1_mu2
ssim_map = ((2*mu1_mu2+C1) * (2*sigmal2+C2)) / ((mu1_sq+mu2_sq+C1) * (sigma1_sq+sigma2_sq+C2))
return np.mean(np.mean(ssim_map))
def img_show(similarity, img1, img2, name1, name2):
# similarity = random.uniform(60,100)
zt = "./Valentine/方正兰亭准黑_GBK.ttf"
my_font = font_manager.FontProperties(fname = zt,size =20 )
img1 = cv2.resize(img1, (520, 520))
img2 = cv2.resize(img2, (520, 520))
imgs = np.hstack([img1, img2])
imgs2 = imgs[:,:, ::-1]
plt.axis('off')
plt.title('{0} VS {1} \n CP指数: {2}%'.format(name1, name2, round(similarity, 2)), fontproperties=my_font)
plt.imshow(imgs2)
path = "a.jpg"
cv2.imwrite(path, imgs)
# img = cv2ImgAddText(imgs, '夫妻相: {}%'.format(round(similarity, 2)), 350, 130, (255, 0 , 0), 50)
# cv2.imshow('image1 vs image2', img)
# cv2.waitKey()
3.修改预置的视频和图片
在Valentine文件夹下,有一个预置的1.png和2.png图片,大家可以将里面的图片替换成自己的,图片的名称不建议修改,如果修改成其他的名称,后面的路径也要进行相应的修改。
点击此处上传你和Ta的照片(不会留存照片信息,推理完成后内存数据会自动清除)
上传成功
if __name__ == '__main__':
name1 = input('请输入图1照片姓名: \n')
name2 = input('请输入图2照片姓名: \n')
img1_path = 'Valentine/1.png'
img2_path = 'Valentine/2.png'
img1 = cv2.imread(img1_path)
img2 = cv2.imread(img2_path)
im1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
im2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
im1 = cv2.resize(im1, (520,520))
im2 = cv2.resize(im2, (520,520))
similarity = compute_ssim(im1, im2)*100
if similarity == 100:
raise ValueError("图片重复! 请重新上传图片")
random.seed(similarity)
add_score = random.uniform(1, 100-similarity)
similarity += add_score
img_show(similarity, img1, img2, name1, name2)
注意:输入图1图2照片姓名后都需要按下回车键
预测成功:
image = Image.open("a.jpg")
image = image.resize((498,278))
4.打印输出海报
import os
from PIL import Image,ImageDraw,ImageFont,ImageFilter
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
填写创作者名称
右键即可下载海报
海报如下: