电子科技大学图像与视频处理(视频部分)课程测试
1、 读取原视频序列(2帧),其中第1帧为I帧,第2帧为P帧;
video_path = "E:/foreman_qcif.y4m" # 注意修改路径
cap = cv2.VideoCapture(video_path)
cap.set(cv2.CAP_PROP_POS_FRAMES,1) #设置要获取的帧号
a,m_I=cap.read() #read方法返回一个布尔值和一个视频帧。若帧读取成功,则返回True0
cap.set(cv2.CAP_PROP_POS_FRAMES,2) #设置要获取的帧号
a,m_p=cap.read()
m_P = m_p - m_I
结果
2、 进行8×8分块的DCT变换;
def dctpad(src):
h, w = src.shape[:2]
h1 = int((h/8+0.5))*8
w1 = int((w/8+0.5))*8
#拷贝到补充的数组
dft_A = np.zeros((h1, w1), dtype=np.float32)
dft_A[:h, :w] = src
return dft_A
def dct_l(image):
#image = m_I[:,:,2]
h,w = image.shape[:2]
print(w,h)
imgf = dctpad(image)
print(imgf.dtype, imgf.shape)
dct = np.zeros_like(imgf)
imsize = imgf.shape
#8x8 DCT
for i in range(0,imgf.shape[0],8):
for j in range(0,imgf.shape[1],8):
dct[i:(i+8),j:(j+8)] = cv2.dct(imgf[i:(i+8),j:(j+8)])
# 显示完整的DCT图像
plt.figure()
plt.imshow(dct,cmap='gray',vmax = np.max(dct)*0.01,vmin = 0)
plt.title( "8x8 DCT的图像")
结果
3、 设定量化步长Qstep=22进行量化;
ratio=22 # 设置量化比率
for i in range(dct.shape[0]):
for j in range(dct.shape[1]):
# for k in range(dct.shape[2]):
dct_thresh[i][j]=(round(dct[i][j]/ratio))
plt.figure()
plt.imshow(dct_thresh,cmap='gray',vmax = np.max(dct)*0.01,vmin = 0)
plt.title( "量化 8x8 DCT 图像")
结果
4、 完成相应的反量化和反DCT变换;
for i in range(dct_thresh.shape[0]):
for j in range(dct_thresh.shape[1]):
dct_thresh[i][j]=(dct_thresh[i][j]*ratio)
plt.figure()
plt.imshow(dct_thresh,cmap='gray',vmax = np.max(dct)*0.01,vmin = 0)
plt.title( "反量化 8x8 DCT 图像")
im_dct = np.zeros(imsize)
# 8x8 IDCT
for i in range(0,im_dct.shape[0],8):
for j in range(0,im_dct.shape[1],8):
im_dct[i:(i+8),j:(j+8)] = cv2.idct(dct_thresh[i:(i+8),j:(j+8)])
结果
5、 讲重组数据写入文件“re_foreman.qcif”(2帧);
m_I1 = np.zeros_like(m_I)
m_P1 = np.zeros_like(m_P)
m_I1[:,:,0]=dct_l(m_I[:,:,0])
m_I1[:,:,1]=dct_l(m_I[:,:,1])
m_I1[:,:,2]=dct_l(m_I[:,:,2])
m_P1[:,:,0]=dct_l(m_P[:,:,0])
m_P1[:,:,1]=dct_l(m_P[:,:,1])
m_P1[:,:,2]=dct_l(m_P[:,:,2])
reforeman1 = np.concatenate((m_I1,m_P1))
cv2.imshow('I',m_I1)
cv2.waitKey()
f = open("reforeman.yuv", "x")
f.write(str(reforeman1))
f.close()
6、 计算“foreman.qcif”和“re_foreman.qcif”的PSNR
# 求PSNR
foreman = np.concatenate((m_I,m_P))
res = np.mean((reforeman1 - foreman) ** 2)
psnr = 20 * np.log10(255.0/ (res)**(1/2))
print(psnr)
结果
33.85399161347282