update
- 使用os copyfile来复制图片代替cv写。
- 增加逻辑,避免图片没有更新情况
- def 函数,更加简洁
#代码
import cv2
from shutil import copyfile
from skimage.metrics import structural_similarity as compare_ssim
import os
import imutils
import matplotlib.pyplot as plt
from datetime import datetime
import time
## img1 原始图片,img2原有图片
## img1 序大图片,img2序小图片
def score_scompare(img1,img2):
spect1 = cv2.imread(img1,flags=1) # flags=1 读取彩色图像(BGR)
spect2 = cv2.imread(img2,flags=1) # flags=1 读取彩色图像(BGR)
grayA = cv2.cvtColor(spect1, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(spect2, cv2.COLOR_BGR2GRAY)
(score, diff) = compare_ssim(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))
return score
def img_cropped(img1):
spect1 = cv2.imread(img1,flags=1) # flags=1 读取彩色图像(BGR)
print("照片大小:", spect1.shape)
scale_cropped = (1-0.88)/4
# 裁剪坐标为[y0:y1, x0:x1],必须为整数
## cropped = spect1[0:spect1.shape[0], round((spect1.shape[1]-spect1.shape[0]*4/3)/2):spect1.shape[1]-round((spect1.shape[1]-spect1.shape[0]*4/3)/2)]
cropped = spect1[round(scale_cropped*3*spect1.shape[0]):round((1-scale_cropped)*spect1.shape[0]), round(scale_cropped*2*spect1.shape[1]):round((1-scale_cropped*2)*spect1.shape[1])]
print("照片裁剪", cropped.shape)
name_cropped = "D:\\jinshan_cropped\\" + localdate + ".jpg"
cv2.imwrite(name_cropped, cropped)
localdate =datetime.now().strftime("%Y%m%d")
print("localdate = ",localdate)
#获取照片的路径
org_img_folder='C:\\Users\chen\AppData\Roaming\Microsoft\Windows\Themes\CachedFiles\\'
#获取照片的名称
daily_img = "CachedImage_1920_1080_POS3.jpg"
file_name1 = org_img_folder + daily_img
#保存照片的路径
raw_img_folder='D:\\jinshan_raw_img\\'
#读取文件夹内照片数。
Filelist = []
files = os.listdir(raw_img_folder)
print("文件夹内照片一共有: ", len(files))
#当没有照片时,直接更新照片
if len(files) == 0:
print("之前没有数据,今日新建数据")
copyfile(file_name1, raw_img_folder + localdate + ".jpg")
img_cropped(file_name1)
#文件名字倒叙
files.sort(reverse=True) #倒叙排序
#当只有一个照片并且时,判断相似度,如果不同,直接更新。
if len(files) == 1:
score = score_scompare(file_name1,raw_img_folder + files[0])
if score < 0.95:
copyfile(file_name1, raw_img_folder + localdate + ".jpg")
img_cropped(file_name1)
else:
print("照片与文件唯一的照片相似度太大,本次不更新!")
#当有2张照片以上
if len(files)>= 2:
if files[0].replace(".jpg","") != localdate:
score = score_scompare(file_name1,raw_img_folder + files[0])
if score >0.95:
print("照片与最近照片相似,可能库尚未更新")
else:
copyfile(file_name1, raw_img_folder + localdate + ".jpg")
img_cropped(file_name1)
print("相片已经更新")
else:
print("今日照片已存在")
score = score_scompare(file_name1,raw_img_folder + files[0])
if score<0.95:
copyfile(file_name1, raw_img_folder + localdate + ".jpg")
img_cropped(file_name1)
print("相片已经更新")
else:
print("相片相似,不更新")
## plt.imshow(cropped)
## plt.show()