目录
一、导出帧图像
将视频以帧图像的方式呈现,逐帧导出图片
import os
os.chdir("C:/Users/Administrator/AppData/Local/Programs/Python/Python37/Lib/site-packages")
import cv2
import subprocess
v_path="D:/Python/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.COLOR_BGR2GRAY)
cv2.imwrite("D:\Python\image{}.jpg".format(i),img)
运行结果示例:
二、判定相似度
对分帧结果判定相似度,并提取出相似度较大镜头作为分镜头。
1.均值哈希判定相似度
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 均值哈希算法
def aHash(img):
# 缩放为8*8
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为hash值初值为''
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
# 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
for i in range(549):
img1=cv2.imread('./pic2/image{}.jpg'.format(i))
img2=cv2.imread('./pic2/image{}.jpg'.format(i+1))
hash1 = aHash(img1)
hash2 = aHash(img2)
n = cmpHash(hash1, hash2)
if(n>22):
print('均值哈希算法相似度:', n/64)
cv2.imwrite('./shot/image{}.jpg'.format(i+1),img2)
运行结果:
(错误识别了3张)
2.基于直方图相似度
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 通过得到RGB每个通道的直方图来计算相似度
def classify_hist_with_split(image1, image2, size=(256, 256)):
# 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值
image1 = cv2.resize(imag