2 Commits
Author SHA1 Message Date
天涯古巷 4d9eaf798d Merge pull request #160 from eritpchy/apple_vision
+ Apple Vision 测试版
2022-09-14 21:52:34 +08:00
Jason 2122c84bf1 + Apple Vision 测试版 2022-09-14 17:31:57 +08:00
10 changed files with 1299 additions and 24 deletions

No files matched your search

+19 -9
View File
@@ -13,7 +13,7 @@ import re
import time
from pathlib import Path
from fsplit.filesplit import Filesplit
from paddle import fluid
# from paddle import fluid
from tools.constant import *
@@ -67,11 +67,11 @@ while not IS_LEGAL_PATH:
# 是否使用GPU
USE_GPU = False
# 如果paddlepaddle编译了gpu的版本
if fluid.is_compiled_with_cuda():
# 查看是否有可用的gpu
if len(fluid.cuda_places()) > 0:
# 如果有GPU则使用GPU
USE_GPU = True
# if fluid.is_compiled_with_cuda():
# # 查看是否有可用的gpu
# if len(fluid.cuda_places()) > 0:
# # 如果有GPU则使用GPU
# USE_GPU = True
# ×××××××××××××××××××× [不要改]判断是否使用GPU start ××××××××××××××××××××
@@ -146,8 +146,18 @@ if REC_CHAR_TYPE in ('ch', 'japan', 'korean', 'en', 'chinese_cht', 'EN_symbol',
# ×××××××××××××××××××× [不要改]读取语言、模型路径、字典路径 end ××××××××××××××××××××
# --------------------- 请根据自己的实际情况改 start-----------------
# 使用快速字幕检测算法(_analyse_subtitle_frame)时,背景颜色
# --------------------- 请根据自己的实际情况改 start-----------------------------
# 是否使用GPU
# 使用GPU可以提速20倍+,你要是有N卡你就改成 True
USE_GPU = False
# 如果paddlepaddle编译了gpu的版本
# if fluid.is_compiled_with_cuda():
# # 查看是否有可用的gpu
# if len(fluid.cuda_places()) > 0:
# # 如果有GPU则使用GPU
# USE_GPU = True
# 使用快速字幕检测算法时,背景颜色
BG_MOD = BackgroundColor.DARK
# 黑色背景被减矩阵阈值
BG_VALUE_DARK = 200
@@ -190,7 +200,7 @@ WATERMARK_AREA_NUM = 5
THRESHOLD_TEXT_SIMILARITY = 0.8
# 字幕提取中置信度低于0.75的不要
DROP_SCORE = 0.75
DROP_SCORE = 0.1
# 字幕区域允许偏差, 0为不允许越界, 0.03表示可以越界3%
SUB_AREA_DEVIATION_RATE = 0
+4 -2
View File
@@ -24,8 +24,6 @@ sys.path.insert(0, os.path.dirname(__file__))
import importlib
import config
from tools.reformat_en import reformat
from tools.infer import utility
from tools.infer.predict_det import TextDetector
from tools.ocr import OcrRecogniser, get_coordinates
from tools import subtitle_ocr
from tools.constant import BackgroundColor
@@ -40,6 +38,8 @@ class SubtitleDetect:
文本框检测类,用于检测视频帧中是否存在文本框
"""
def __init__(self):
from tools.infer import utility
from tools.infer.predict_det import TextDetector
# 获取参数对象
importlib.reload(config)
args = utility.parse_args()
@@ -238,6 +238,7 @@ class SubtitleExtractor:
ocr_args_list = []
compare_ocr_result_cache = {}
tbar = tqdm(total=int(self.frame_count), unit='f', position=0, file=sys.__stdout__)
sub_detector = SubtitleDetect()
while self.video_cap.isOpened():
ret, frame = self.video_cap.read()
# 如果读取视频帧失败(视频读到最后一帧)
@@ -313,6 +314,7 @@ class SubtitleExtractor:
last_total_ms = 0
processed_image = set()
rgb_images_path = os.path.join(self.temp_output_dir, 'RGBImages')
frame_no = 0
while self.vsf_running and not self.isFinished:
# 如果还没有rgb_images_path说明vsf还没处理完
if not os.path.exists(rgb_images_path):
+80
View File
@@ -0,0 +1,80 @@
""" Use Apple's Vision Framework via PyObjC to detect text in images """
import pathlib
import Quartz
import Vision
from Cocoa import NSURL
from Foundation import NSDictionary
# needed to capture system-level stderr
from wurlitzer import pipes
import time
from pprint import pprint
import cv2
from tools.pyci import cimg
class OcrRecogniser:
def __init__(self):
self.results = []
self.handler = make_request_handler(self.results)
self.vision_request = Vision.VNRecognizeTextRequest.alloc().initWithCompletionHandler_(self.handler)
self.vision_request.setRecognitionLanguages_(['zh-CN', 'en'])
#self.vision_request.setRecognitionLevel_(0)
self.vision = Vision.VNImageRequestHandler.alloc()
def predict(self, image):
# a = time.time()
self.height, self.width = image.shape[0:2]
# img_path = "/Users/jason/tmp/1.raw"
# cv2.imwrite(img_path, image, [cv2.IMWRITE_PNG_COMPRESSION, 0])
#
# b = time.time()
# print(b-a)
# input_url = NSURL.fileURLWithPath_(img_path)
# with pipes() as (out, err):
# # capture stdout and stderr from system calls
# # otherwise, Quartz.CIImage.imageWithContentsOfURL_
# # prints to stderr something like:
# # 2020-09-20 20:55:25.538 python[73042:5650492] Creating client/daemon connection: B8FE995E-3F27-47F4-9FA8-559C615FD774
# # 2020-09-20 20:55:25.652 python[73042:5650492] Got the query meta data reply for: com.apple.MobileAsset.RawCamera.Camera, response: 0
# input_image = Quartz.CIImage.imageWithContentsOfURL_(input_url)
input_image = cimg(image).ciimage
vision_options = NSDictionary.dictionaryWithDictionary_({})
vision_handler = self.vision.initWithCIImage_options_(
input_image, vision_options
)
error = vision_handler.performRequests_error_([self.vision_request], None)
# vision_handler.dealloc()
return [], self.results
def get_coordinates(self, dt_box):
coordinate_list = list()
for result in self.results:
xmin, ymin, xmax, ymax = result[2][0:4]
xmin = xmin * self.width
xmax = xmax * self.width
ymin = self.height - ymin * self.height
ymax = self.height - ymax * self.height
coordinate_list.append((xmin, xmax, ymin, ymax))
return coordinate_list
def make_request_handler(results):
""" results: list to store results """
if not isinstance(results, list):
raise ValueError("results must be a list")
def handler(request, error):
if error:
print(f"Error! {error}")
else:
observations = request.results()
results.clear()
for text_observation in observations:
recognized_text = text_observation.topCandidates_(1)[0]
xmin = text_observation.topLeft().x
ymin = text_observation.topLeft().y
xmax = text_observation.bottomRight().x
ymax = text_observation.bottomRight().y
results.append([recognized_text.string(), recognized_text.confidence(), (xmin, ymin, xmax, ymax)])
return handler
+8 -2
View File
@@ -21,14 +21,19 @@ import numpy as np
import paddle
from PIL import Image, ImageDraw, ImageFont
import math
from paddle import inference
# from paddle import inference
import time
from ppocr.utils.logging import get_logger
# from ppocr.utils.logging import get_logger
def str2bool(v):
return v.lower() in ("true", "t", "1")
def parse_args():
return []
def str2bool(v):
return v.lower() in ("true", "t", "1")
def init_args():
parser = argparse.ArgumentParser()
@@ -144,6 +149,7 @@ def parse_args():
def create_predictor(args, mode, logger):
from paddle import inference
if mode == "det":
model_dir = args.det_model_dir
elif mode == 'cls':
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
set -e
cd ${0%/*}/../../
rm -rf ./out | true
python -m nuitka \
--standalone \
--windows-disable-console \
--lto=no \
--include-data-dir=backend=backend \
--include-data-dir=$CONDA_PREFIX/lib/python3.8/site-packages=dependencies \
--include-data-dir=$CONDA_PREFIX/lib/python3.8/tkinter=dependencies/tkinter \
--include-data-dir=$CONDA_PREFIX/lib/python3.8/email=dependencies/email \
--include-data-dir=$CONDA_PREFIX/lib/python3.8/http=dependencies/http \
--include-data-dir=$CONDA_PREFIX/lib/python3.8/distutils=dependencies/distutils \
--include-data-dir=$CONDA_PREFIX/lib/python3.8/unittest=dependencies/unittest \
--include-data-file=$CONDA_PREFIX/lib/python3.8/*.py=dependencies/ \
--include-data-file=$CONDA_PREFIX/lib/python3.8/lib-dynload/_tkinter.cpython-38-darwin.so=dependencies/_tkinter.cpython-38-darwin.so \
--nofollow-imports \
--windows-icon-from-ico=./design/vse.ico \
--plugin-enable=tk-inter,multiprocessing \
--output-dir=out \
./gui.py
+8 -6
View File
@@ -1,15 +1,14 @@
from tools.infer import utility
from tools.infer.predict_system import TextSystem
import config
import importlib
# 加载文本检测+识别模型
class OcrRecogniser:
def __init__(self):
import config
import importlib
from tools.infer.predict_system import TextSystem
# 获取参数对象
importlib.reload(config)
self.args = utility.parse_args()
self.args = []
self.recogniser = self.init_model()
@staticmethod
@@ -95,6 +94,9 @@ class OcrRecogniser:
self.args.rec_char_type = config.REC_CHAR_TYPE
return TextSystem(self.args)
def get_coordinates(self, dt_box):
return get_coordinates(dt_box)
def get_coordinates(dt_box):
"""
File diff suppressed because it is too large. Load diff
+3 -5
View File
@@ -4,7 +4,8 @@ from multiprocessing import Queue, Process
import cv2
from PIL import ImageFont, ImageDraw, Image
from tqdm import tqdm
from tools.ocr import OcrRecogniser, get_coordinates
from tools.apple_vision import OcrRecogniser
#from tools.ocr import OcrRecogniser
from tools.constant import SubtitleArea
from tools import constant
from threading import Thread
@@ -29,7 +30,7 @@ def extract_subtitles(data, text_recogniser, img, raw_subtitle_file,
dt_box, rec_res = text_recogniser.predict(img)
# rec_res格式为: ("hello", 0.997)
# 获取文本坐标
coordinates = get_coordinates(dt_box)
coordinates = text_recogniser.get_coordinates(dt_box)
# 将结果写入txt文本中
if options.REC_CHAR_TYPE == 'en':
# 如果识别语言为英文,则去除中文
@@ -274,6 +275,3 @@ def frame_preprocess(subtitle_area, frame):
frame = frame[:cropped]
return frame
if __name__ == "__main__":
pass
+5
View File
@@ -7,6 +7,10 @@
"""
import backend.main
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dependencies'))
import site
site.USER_SITE=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dependencies')
import configparser
import PySimpleGUI as sg
import cv2
@@ -521,6 +525,7 @@ class LanguageModeGUI:
if __name__ == '__main__':
sys.argv = [os.path.join(os.path.dirname(os.path.abspath(__file__)), 'backend/main.py')]
try:
multiprocessing.set_start_method("spawn")
# 运行图形化界面
+57
View File
@@ -0,0 +1,57 @@
astor==0.8.1
certifi==2021.10.8
chardet==4.0.0
charset-normalizer==2.0.12
click==8.1.2
cycler==0.11.0
decorator==5.1.0
dill==0.3.4
filesplit==3.0.2
fonttools==4.32.0
future==0.18.2
gast==0.3.3
idna==3.3
imageio==2.13.3
imgaug==0.4.0
kiwisolver==1.3.2
lmdb==1.2.1
matplotlib==3.5.1
multiprocess==0.70.12.2
networkx==2.6.3
Nuitka==0.7.7
numpy==1.19.3
opencc-python-reimplemented==0.1.6
opencv-python==4.5.4.60
packaging==21.3
paddlepaddle==2.2.2
pefile==2021.9.3
Pillow==8.4.0
protobuf==3.19.1
pyclipper==1.3.0.post2
pyobjc-core==8.5
pyobjc-framework-Cocoa==8.5
pyobjc-framework-CoreML==8.5
pyobjc-framework-Quartz==8.5
pyobjc-framework-Vision==8.5
pyparsing==3.0.6
PySimpleGUI==4.55.1
pysrt==1.1.2
python-dateutil==2.8.2
python-Levenshtein-wheels==0.13.2
PyWavelets==1.2.0
QPT==1.0b3.dev7
requests==2.26.0
scikit-image==0.19.1
scipy==1.7.3
Shapely==1.8.0
six==1.16.0
tifffile==2021.11.2
tk==0.1.0
tqdm==4.63.1
ttkbootstrap==0.5.1
urllib3==1.26.7
wget==3.2
whych==0.2.1
wordsegment==1.3.1
wurlitzer==3.0.2
zstandard==0.17.0