Python を使用してビデオから字幕を抽出する
``
1.ガイドパッケージ
import base64
import os
import cv2
import requests
import aip
from aip import AipOcr
1.cv2エラー
解決策: Anaconda Prompt を開き、pip install opencv-python と入力して、インストールを待ちます。
-
aip エラー
の解決策: pip install Baidu-aip -
anaconda パッケージを使用File–> Settings–>Project Interpreter in pycharm
Anacondad のインストール パスで python.exe を見つければ問題ありません。
2. ビデオを分析する
動画から10フレーム間隔で写真を撮る
def VLink():
video_path = 'D:/Resource/MaxFish.mp4' # 视频地址
images_path = 'D:/Resource/images/' # 图片输出文件夹
interval = 10 # 每间隔10帧取一张图片
num = 1
vid = cv2.VideoCapture(video_path)#打开这个视频
while vid.isOpened():
is_read, frame = vid.read() #按帧读取视频 frame是读取图像 is_read是布尔值。文件读取到结尾返回FALSE
if is_read:
file_name = num
cv2.imwrite(images_path + str(file_name) + '.jpg', frame)
cv2.waitKey(1)
num += 1
else:
break
結果:
3.字幕を傍受する
写真の字幕部分を切り取る
def tailor(path1,path2,begin ,end,step_size):
for i in range(begin,end,step_size):
fname1 = path1%str(i)
print(fname1)
img = cv2.imread(fname1) #像素
print(img.shape)
cropped = img[650:720, 300:1024] # 裁剪坐标为[y0:y1, x0:x1]
imgray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
thresh = 200
ret, binary = cv2.threshold(imgray, thresh, 255, cv2.THRESH_BINARY)
binary1 = cv2.bitwise_not(binary)
cv2.imwrite(path2 % str(i), binary1)
cropped = img[650:720, 300:1024]这里的截取可能因为照片的大小不同而不同,可以编辑照片,看一下适合字幕截取的位置。例如:
マウスの動きによって傍受された画像の位置を知る。
結果:
第四に、絵を分析する
画像を分析し、サブタイトルを取得して、TXT ファイルに保存します。
1、
def subtitle(fname,begin,end,step_size):
array =[] #定义一个数组用来存放words
for i in range(begin,end,step_size):
fname1 = fname % str(i) #字幕image D:/Resource/images/img_subtitle/100.jpg
with open(fname1, 'rb') as fp:
image = base64.b64encode(fp.read())
try:
results = requestApi(image)["words_result"] #调用requestApi函数,获取json字符串中的words_result
for item in results:
print(results)
array.append(item['words'])
except Exception as e:
print(e)
text=''
result = list(set(array)) # 去重
result.sort(key=array.index) # 排序
for item in result:
text +=item+'\n'
2、
# 定义一个函数,用来访问百度API,
def requestApi(img):
general_word_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
params = {
"image": img,
"language_type": "CHN_ENG"}
access_token = '24.80669db308b385e6f913e40b3fe604d1.2592000.1651237616.282335-25877315'
request_url = general_word_url + "?access_token=" + access_token
headers = {
'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
results = response.json()
return results
Baidu Smart Cloud:
URL: https://login.bce.baidu.com
クリックしてアプリケーションを作成し、名前を書き込めば作成は成功です。
ここでは、API キーと秘密キーを確認できます。取得するには、これら 2 つのパラメーターを使用する必要があります。
左側のナビゲーション バーにある技術文書をクリックしてください----> API ドキュメント----->一般的なシーンのテキスト認識------>標準バージョンを選択して
、アクセスの取得方法を教えてください。トークン。
リンクをコピー: https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=mGAOwUKl42RM93TAWEmHZ3ff&client_secret=RGlbvPF49FGpqLiMVhFow1xfXp4EAvWAA&
ここでの grant_type は client_credentials
client_id === API Key
client_secret == Secret Keyとして固定されています
自分で適用した API キーとシークレット キーを置き換え、Enter キーを押して access_token を取得するだけです
。
コード内で access_token を見つけたい場合。次のようになります。
def get_access_token():
url = 'https://aip.baidubce.com/oauth/2.0/token'
data = {
'grant_type': 'client_credentials', # 固定值
'client_id': 'eFGwDIb*******HucbnPr', # API Key
'client_secret': 'XPxWT2L********PFVCKS6PVih' # Secret Key
}
res = requests.post(url, data=data)
res = res.json()
print(res)
access_token = res['access_token']
return access_token
問題: KeyError: 'words_result'
解決策:
(1) Baidu Smart Cloud に入り、クリックして無料のリソースを受け取ります
(2) 入場後、一般的なシーン認識を行い、「すべて」を選択して受け取ります (ここでは、既に受け取っているため、表示されません) (3) 受け取り後、元の場所に戻ります先ほどインターフェースを開き、
「資源リスト」を確認すると、受け取った資源が表示されます。
(4) 使用後もこの状況が続く場合は、https: //aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic
?access_token=24.80669db308b385e6f913e40b3fe604d1.2592000.1651237616.282335-25877322 を検索してください
。 17ですと実名認証が可能になり、通話回数が増えます。
3.
D:/Resource/配下にsubtitle.txtを作成し、抽出した字幕を書き込みます。
#创建文本
def text_create( msg):
full_path = "D:/Resource/subtitle.txt" # 也可以创建一个.doc的word文档
file = open(full_path, 'w',encoding='utf-8')
file.write(msg)
file.close()
五、主な機能
if __name__ == '__main__':
path1 = 'D:/Resource/images/%s.jpg' # 视频转为图片存放的路径(帧)
path2 = 'D:/Resource/images/img_subtitle/%s.jpg' # 图片截取字幕后存放的路径
print("""
1..裁剪视频
2.图片裁剪
3.提取字幕
""")
choose = input()
begin = 100
end = 1000
step_size = 10
if choose == '1': #视频中提取图片
VLink()
if choose == '2': #提取字幕
tailor(path1, path2, begin, end, step_size)
if choose == '3': #提取字
subtitle(path2, begin, end, step_size)
参考:https://blog.csdn.net/qq_39783601/article/details/105748486