用brew Install安装tesseract
路径:/usr/local/Cellar/tesseract/4.1.1
把语言文件复制到tessdata里
/usr/local/Cellar/tesseract/4.1.1/share/tessdata
安装pytesseract:pip3 install pytesseract
!!!很重要!!!一定要配置tesseract环境!!!
在终端输入
export TESSDATA_PREFIX=/usr/local/Cellar/tesseract/4.1.1/share/tessdata
export PATH=$PATH:$TESSDATA_PREFIX
字幕识别代码
第一段:
import pytesseract
import cv2
import numpy as np
from scipy import stats
import os
import matplotlib.pyplot as plt
if __name__=='__main__':
path="20210701.mp4"
print(path)
cap=cv2.VideoCapture(path)
frame_count=int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(frame_count)
i=0
while i<frame_count:
cap.set(cv2.CAP_PROP_POS_FRAMES, i)
_, frame = cap.read(i)
if i==48:
cv2.imwrite('20210701.jpg',frame)
shape = frame.shape
print(shape)
#cv2.imshow("Frame-1", frame[580:630, 10:1270])
#plt.imshow(frame)
#plt.axis("off")
#plt.show()
img=frame[630:680, 50:1270]
plt.imshow(img)
plt.axis("off")
plt.show()
i=i+24*2
生成出每一帧的字幕部分图片
第二段
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("Frame-2:Gray", img)
_,img=cv2.threshold(img,220,225,cv2.THRESH_BINARY)
tessdata_dir_config='--tessdata-dir "/usr/local/Cellar/tesseract/4.1.1/share/tessdata" --psm 7 -c preserve_interword_spaces=1'
word=pytesseract.image_to_string(img,lang='chi_sim',config=tessdata_dir_config)
print(word)
if cv2.waitKey(10)&0xff==ord("q"):
break
cap.release()
cv2.destroyAllWindows()
生成识别出的字幕
(可能是因为我mac电脑安装的版本不够高,所以出现很多乱码)
完整的代码如下:
import pytesseract
import cv2
import numpy as np
from scipy import stats
import os
import matplotlib.pyplot as plt
if __name__=='__main__':
path="20210701.mp4"
print(path)
cap=cv2.VideoCapture(path)
frame_count=int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(frame_count)
i=0
while i<frame_count:
cap.set(cv2.CAP_PROP_POS_FRAMES, i)
_, frame = cap.read(i)
if i==48:
cv2.imwrite('20210701.jpg',frame)
shape = frame.shape
print(shape)
#cv2.imshow("Frame-1", frame[580:630, 10:1270])
#plt.imshow(frame)
#plt.axis("off")
#plt.show()
img=frame[630:680, 50:1270]
plt.imshow(img)
plt.axis("off")
plt.show()
i=i+24*2
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("Frame-2:Gray", img)
_,img=cv2.threshold(img,220,225,cv2.THRESH_BINARY)
tessdata_dir_config='--tessdata-dir "/usr/local/Cellar/tesseract/4.1.1/share/tessdata" --psm 7 -c preserve_interword_spaces=1'
word=pytesseract.image_to_string(img,lang='chi_sim',config=tessdata_dir_config)
print(word)
if cv2.waitKey(10)&0xff==ord("q"):
break
cap.release()
cv2.destroyAllWindows()
!!!在输入代码的时候最好一行一行运行,不然很容易出现各种各样的报错!!!