一、视频转化为图片并比较图片相似度
1.视频转化为图片
注:需要在文件夹里新建一个文件夹装选取出来的图片
import os
import cv2
import subprocess
os.chdir('C:\\Users\\读书人mn\\Desktop\\123123')
v_path ='ghz.mp4'
image_save ='.pic'
cap=cv2.VideoCapture(v_path)
frame_count=cap.get(cv2.CAP_PROP_FRAME_COUNT)
for i in range(int(frame_count)):
_,img=cap.read()
#img=cv2.cvtColor(img,cv2.cv2.COLOR_BGR2GRAY)
cv2.imwrite('.pic\\image{}.jpg'.format(i),img)
2.利用numpy、哈希等判断图像是否相同
True表示相同,False表示不相同
3.基于哈希判断图像相似度
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
os.chdir('C:\\Users\\读书人mn\\Desktop\\123123')
def aHash(img):
plt.imshow(img)
plt.axis('off')
plt.show()
img=cv2.resize(img,(8,8))
plt.imshow(img)
plt.axis('off')
plt.show()
#转换为灰度图
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
s=0
hash_str=''
# 遍历累加求像素和
for i in range(8):
for j in range(8):
s = s + gray[i, j]
# 求平均灰度
avg = s / 64
# 灰度大于平均值为1相反为0生成图片的hash值
for i in range(8):
for j in range(8):
if gray[i, j] > avg:
hash_str = hash_str + '1'
else:
hash_str = hash_str + '0'
return hash_str
# 通过得到RGB每个通道的直方图来计算相似度
def classify_hist_with_split(image1, image2, size=(256, 256)):
# 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值
image1 = cv2.resize(image1, size)
image2 = cv2.resize(image2, size)
plt.imshow(image1)
plt.show()
plt.axis('off')
plt.imshow(image2)
plt.show()
plt.axis('off')
sub_image1 = cv2.split(image1)
sub_image2 = cv2.split(image2)
sub_data = 0
for im1, im2 in zip(sub_image1, sub_image2):
sub_data += calculate(im1, im2)
sub_data = sub_data / 3
return sub_data
# 计算单通道的直方图的相似值
def calculate(image1, image2):
hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
plt.plot(hist1, color="r")
plt.plot(hist2, color="g")
plt.show()
# 计算直方图的重合度
degree = 0
for i in range(len(hist1)):
if hist1[i] != hist2[i]:
degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
else:
degree = degree + 1 #统计相似
degree = degree / len(hist1)
return degree
# Hash值对比
def cmpHash(hash1, hash2):
n = 0
print(hash1)
print(hash2)
# hash长度不同则返回-1代表传参出错
if len(hash1)!=len(hash2):
return -1
# 遍历判断
for i in range(len(hash1)):
# 不相等则n计数+1,n最终为相似度
if hash1[i] != hash2[i]:
n = n + 1
return n
img1 = cv2.imread('.pic\\image0.jpg') # 11--- 16 ----13 ---- 0.43
img2 = cv2.imread('.pic\\image1.jpg')
hash1 = aHash(img1)
hash2 = aHash(img2)
n = cmpHash(hash1, hash2)
print('均值哈希算法相似度:', n)
n = classify_hist_with_split(img1, img2)
print('三直方图算法相似度:', n)
from PIL import Image
for i in range(549):
img1=cv2.imread('.pic/image{}.jpg'.format(i))
img2=cv2.imread('.pic/image{}.jpg'.format(i+1))
hash1=aHash(img1)
hash2=aHash(img2)
n=cmpHash(hash1,hash2)
if (n>32):
print('均值哈希算法相似度:',n/64)
cv2.imwrite('short/image{}.jpg'.format(i+1),img2)
结果如下:
二、视频截取
首先,打开cmd,利用“cd +决定路径”方式准确将cmd定位到ffmpeg所在的位置
其次,输入ffmpeg -i 视频路径 -ss 开始时间 -t 需要截取的时间 -vcodec copy -acodec copy -preset superfast 输出视频名称.mp4
结果如下:
注:目前利用本段代码截取出来的视频存在声画不对位的问题,画面会比声音出现更早一些