# 寻找文件夹中重复的文件import cv2
import os
import sys
PIC_PATH ="./"
width, height =100,100
pic_file = os.listdir(PIC_PATH)
same_pic_index =[]
imgs =[]
has_same =set()
count =len(pic_file)# 如果图片的数量为0if count ==0:print("没有图像")# 退出程序
sys.exit(0)# 遍历照片文件for file_name in pic_file:# 拼接完整文件名
file_name = PIC_PATH + file_name
# 创建文件的图像
img = cv2.imread(file_name)# 缩放成统一大小
img = cv2.resize(img,(width, height))
imgs.append(img)# 遍历所有图像文件不遍历最后一个图像for i inrange(0, count -1):# 如果此图像已经找到相同的图像if i in has_same:continue# 取出模板图像
templ = imgs[i]# 与templ内容相同的图像索引列表
same =[i]# 从templ的下一个位置开始遍历for j inrange(0+ i +1, count):# 如果此图像已经找到相同的图像if j in has_same:continue
pic = imgs[j]
result = cv2.matchTemplate(pic, templ, cv2.TM_SQDIFF_NORMED)if result >0.9:
same.append(j)
has_same.add(i)
has_same.add(j)iflen(same)>1:
same_pic_index.append(same)for same_list in same_pic_index:
text ="相同的照片"for same in same_list:
text +=str(pic_file[same])+","print(text)
demo3
# 多模板匹配import cv2
# 读取原始图像
img = cv2.imread("./orig/hz.jpg")
img = cv2.resize(img,None,None,0.2,0.2)# cv2.imwrite("./orig/hz.jpg", img)# 读取模板图像
rh = cv2.imread("./template/rh.png")
height, width, c = rh.shape
# 按照标准相关系数匹配
result = cv2.matchTemplate(img, rh, cv2.TM_CCORR_NORMED)for y inrange(len(result)):for x inrange(len(result[y])):if result[y][x]>0.85:
cv2.rectangle(img,(x, y),(x + width, y + height),(0,0,255),2)
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
demo4
import cv2
# 多模板匹配defmyMatchTemplate(img, templ):
height, width, c = templ.shape
results = cv2.matchTemplate(img, templ, cv2.TM_CCORR_NORMED)
loc =list()for i inrange(len(results)):for j inrange(len(results[i])):if results[i][j]>0.92:
loc.append((j, i, j + width, i + height))return loc
img = cv2.imread("./orig/hz.jpg")
templs =list()
templs.append(cv2.imread("./template/phl.png"))
templs.append(cv2.imread("./template/rh.png"))
templs.append(cv2.imread("./template/shy.png"))
loc =list()for t in templs:
loc += myMatchTemplate(img, t)for i in loc:
cv2.rectangle(img,(i[0], i[1]),(i[2], i[3]),(0,0,255),2)
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()