【3】Python 视频文字识别提取 - json2txt

  json2txt.py

## simple_srt.py

from datetime import timedelta
from datetime import datetime


def us_to_string(microseconds):
    return (datetime(1, 1, 1) + timedelta(microseconds=microseconds)).strftime('%H:%M:%S') + ',' + str((microseconds % 10**6) // 10**3).zfill(3)


def tracks_to_srt_list(tracks):
    tracks.sort(key=lambda t: t['start'])

    tracks_in_string = []
    for i, t in enumerate(tracks):
        tracks_in_string.append(
            '\n'.join([str(i+1),
                       us_to_string(t['start']) + ' ---> ' +
                       us_to_string(t['end']),
                       t['content']])
        )

    return tracks_in_string


def tracks_to_srt_string(tracks):
    return '\n\n'.join(tracks_to_srt_list(tracks))


## draft_content.py


import json


def draft_content_to_tracks(draft_content):
    texts = {t['id']: t['content']
             for t in draft_content['materials']['texts']
             if t['type'] == 'subtitle'}

    """[
        'start': (μs),
        'end': (μs),
        'content': (...)
    }]"""
    tracks = []
    for t in draft_content['tracks']:
        for s in t['segments']:
            if s['material_id'] in texts.keys():
                timerange = s['target_timerange']
                tracks.append({
                    'start': timerange['start'],
                    'end': timerange['start'] + timerange['duration'],
                    'content': texts[s['material_id']]
                })

    return tracks


def read_draft_content_src(directory):
    with open(directory, 'r', encoding='utf-8') as f:
        draft_content = json.loads(f.read())

    print(draft_content)
    return draft_content_to_tracks(draft_content)



# if __name__ == '__main__':
#     print(r'''剪映的草稿文件一般位于 C:\Users\您的用户名\AppData\Local\JianyingPro\User Data\Projects 。''')
#
#     draft_content_directory = input("请输入 draft_content.json 的地址>>")
#     if not draft_content_directory:
#         draft_content_directory = r'C:\Users\wangjun\AppData\Local\JianyingPro\User Data\Projects\com.lveditor.draft\202108251454\draft_content.json'
#
#     tracks = read_draft_content_src(draft_content_directory)
#
#     with open('./subtitles.srt', 'w', encoding='utf-8') as f:
#         f.write(tracks_to_srt_string(tracks))
#
#     input('请查收 subtitles.srt。')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,你可以使用以下两种方式识别图片中的文字: 1. 使用OCR库(Optical Character Recognition)进行文字识别,其中Tesseract OCR是最流行的免费OCR库之一。你需要使用以下命令安装Tesseract OCR: ``` pip install pytesseract ``` 然后,你可以使用以下代码来识别图片中的文字: ```python import pytesseract from PIL import Image img = Image.open('image.png') text = pytesseract.image_to_string(img) print(text) ``` 其中,'image.png'是要识别的图片文件名,image_to_string()方法将文字从图片中提取出来。 2. 使用AI模型进行文字识别,如Google Cloud Vision API或Amazon Rekognition。这些服务需要API密钥,并且通常需要付费使用。你可以使用以下代码来使用Google Cloud Vision API进行文字识别: ```python import io import os from google.cloud import vision from google.cloud.vision import types os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'path\to\google\cloud\api\key.json' client = vision.ImageAnnotatorClient() with io.open('image.png', 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.text_detection(image=image) texts = response.text_annotations for text in texts: print(text.description) ``` 在这里,你需要替换'path\to\google\cloud\api\key.json'为你自己的Google Cloud API密钥文件路径。然后,你可以使用text_detection()方法来识别图片中的文字,并使用text_annotations属性来获取识别结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值