Python3使用CV2、PIL提升视频画质

有一段很多年前的太极拳教学演示视频,在大屏幕电视播放,视频画面实在让人看不下去,就想有什么办法提高视频画质,安装Topaz Video Enhance AI软件可以实现,但我还是喜欢自己折腾python,直接记录折腾笔记。

安装pillow和opencv-python

1
2
pip3 install opencv-python
pip3 install pillow

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import cv2
from PIL import ImageEnhance, Image
import numpy as np
cap = cv2.VideoCapture('/Users/mymac/Movies/太极拳/24式整套 .mp4')
images = []
def img\_enhance(image):
# 亮度增强
enh\_bri = ImageEnhance.Brightness(image)
brightness = 1.2
image\_brightened = enh\_bri.enhance(brightness)
# image\_brightened.show()
# 色度增强
enh\_col = ImageEnhance.Color(image\_brightened)
color = 1.2
image\_colored = enh\_col.enhance(color)
# image\_colored.show()
# 对比度增强
enh\_con = ImageEnhance.Contrast(image\_colored)
contrast = 1.2
image\_contrasted = enh\_con.enhance(contrast)
# image\_contrasted.show()
# 锐度增强
enh\_sha = ImageEnhance.Sharpness(image\_contrasted)
sharpness = 1.2
image\_sharped = enh\_sha.enhance(sharpness)
# image\_sharped.show()
return image\_sharped
while (cap.isOpened()):
ret, frame = cap.read() # 读出来的frame是ndarray类型
image = Image.fromarray(np.uint8(frame)) # 转换成PIL可以处理的格式
images.append(image)
cv2.imshow('frame', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
# 同步进行增强画质处理,并显示
image\_enhanced = img\_enhance(image) # 调用编写的画质增强函数
cv2.imshow('frame\_enhanced', np.asarray(image\_enhanced)) # 显示的时候要把格式转换回来
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()