Python 基于哈希和直方图的视频图像处理
发布时间
阅读量:
阅读量
图像处理
一、导入库
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
from PIL import Image
os.chdir('视频所在位置')
二、均值哈希算法处理图像
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)):
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')
# 计算直方图的重合度
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)):
if hash1[i]!=hash2[i]:
n=n+1
return n
六、结果
img1=cv2.imread('PythonAds2021/.pic/image0.jpg')
img2=cv2.imread('PythonAds2021/.pic/image1.jpg')
hash1=aHash(img1)
hash2=aHash(img2)
n=cmpHash(hash1,hash2)
print('均值哈希算法相似度:',n)
n=classify_hist_with_split(img1,img2)
print('三直方图算法相似度:',n)
1、哈希算法

2、三直方图算法


3、RGB通道算法



视频处理
一、基于哈希算法
遍历求相似度,并将一定相似度的图像保存到.shot文件夹
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('.shot/image{}.jpg'.format(i+1),img2)
运行结果:

FFMPEG截取视频
- 通过在CMD中执行“cd +指定路径”指令精准定位CMD至ffmpeg所在的目录位置。
- 运行ffmpeg命令,并依次指定各项参数:输入视频文件路径、起始时间、时长、编码方式(both copy)以及设置超快预设以输出指定名称的mp4文件。

遇到问题:声画不一致,目前还未解决
全部评论 (0)
还没有任何评论哟~
