baoshiwei
2025-04-15 776a127b8db01cd4338f4db2a84ea567a65bff9f
rjuq
已添加12个文件
已修改3个文件
1075 ■■■■■ 文件已修改
camera_onnx.py 101 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
detect_onnx.py 220 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
onnx-test.py 50 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
onnx_predit.py 364 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pachong.py 36 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
paherbbaidu.py 46 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pc.py 35 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
quchong.py 15 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
replaceLabelNumber.py 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
save_img.py 29 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shot_onnx.py 105 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
speech/deepSpeechTest.py 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
speech/formatmp3.py 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
speech/whisper2.py 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
speech/whisperTest.py 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
camera_onnx.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,101 @@
import cv2
import time
import numpy as np
import onnxruntime
from scipy.special import softmax
# åŠ è½½ONNX模型
session = onnxruntime.InferenceSession("model/classify/s.onnx")
# æ‘„像头索引号,通常为0表示第一个摄像头
camera_index = 0
# æ‰“开摄像头
cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
# è®¾ç½®åˆ†è¾¨çއ
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)  # å®½åº¦
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)  # é«˜åº¦
# æ£€æŸ¥æ‘„像头是否成功打开
if not cap.isOpened():
    print("无法打开摄像头")
    exit()
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print("摄像头分辨率:", width, "x", height)
# ä»Žres.json中读取类别
with open("res1-2.json", "r") as f:
    classes = eval(f.read())
# ç›®æ ‡å›¾åƒå°ºå¯¸
target_width = 1024
target_height = 768
# è®¡æ—¶å™¨
start_time = time.time()
# å¾ªçŽ¯è¯»å–æ‘„åƒå¤´ç”»é¢
while True:
    ret, frame = cap.read()
    if not ret:
        print("无法读取摄像头画面")
        break
    # 1920*1080的图像,中心裁剪640*480的区域
    cropped_frame = frame[int(height / 2 - target_height / 2):int(height / 2 + target_height / 2),
                    int(width / 2 - target_width / 2):int(width / 2 + target_width / 2)]
    # è°ƒæ•´å›¾åƒå°ºå¯¸
    resized_frame = cv2.resize(cropped_frame, (target_width, target_height))
    # èŽ·å–å½“å‰æ—¶é—´
    current_time = time.time()
    #如果距离上一次保存已经过去1秒,则保存当前画面
    # if current_time - start_time >= 3.0:
    #     # ç”Ÿæˆä¿å­˜æ–‡ä»¶åï¼Œä»¥å½“前时间命名
    #     save_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".jpg"
    #     # ä¿å­˜è°ƒæ•´å°ºå¯¸åŽçš„图片
    #     cv2.imwrite(save_path + save_name, frame)
    #     print("保存图片:", save_name)
    #     # é‡ç½®è®¡æ—¶å™¨
    #     start_time = time.time()
    # é¢„处理
    blob = cv2.dnn.blobFromImage(resized_frame, 1 / 255.0, (640, 640), swapRB=True, crop=False)
    # æ¨¡åž‹æŽ¨ç†
    outputs = session.run(None, {session.get_inputs()[0].name: blob})
    # print(outputs)
    # åº”用softmax函数
    probabilities = outputs[0]
    # æ‰¾åˆ°æœ€å¤§æ¦‚率的类别
    predicted_class = np.argmax(probabilities, axis=1)[0]
    max_probability = np.max(probabilities, axis=1)[0]
    # æ‰¾åˆ°æ¦‚率较高的前十个类别
    top_ten_classes = np.argsort(probabilities, axis=1)[0][-5:]
    # è¾“出前十个类别
    print("Top 5 Classes:")
    for i in top_ten_classes:
        print(f"{classes[i]}: {probabilities[0][i]}")
    # æ˜¾ç¤ºç”»é¢
    cv2.imshow("Camera", resized_frame)
    # æ£€æµ‹æŒ‰é”®ï¼Œå¦‚果按下q键则退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# å…³é—­æ‘„像头
cap.release()
# å…³é—­æ‰€æœ‰çª—口
cv2.destroyAllWindows()
detect_onnx.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,220 @@
import time
import cv2
import numpy as np
import onnxruntime
class YOLOv8:
    def __init__(self, path, conf_thres=0.7, iou_thres=0.7):
        self.conf_threshold = conf_thres
        self.iou_threshold = iou_thres
        # Initialize model
        self.initialize_model(path)
    def __call__(self, image):
        return self.detect_objects(image)
    def initialize_model(self, path):
        self.session = onnxruntime.InferenceSession(path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
        # Get model info
        self.get_input_details()
        self.get_output_details()
    def detect_objects(self, image):
        input_tensor, ratio = self.prepare_input(image)
        # Perform inference on the image
        outputs = self.inference(input_tensor)
        self.boxes, self.scores, self.class_ids = self.process_output(outputs, ratio)
        return self.boxes, self.scores, self.class_ids
    def prepare_input(self, image):
        self.img_height, self.img_width = image.shape[:2]
        input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        # Resize图片不要直接使用resize,需要按比例缩放,空白区域填空纯色即可
        input_img, ratio = self.ratioresize(input_img)
        # Scale input pixel values to 0 to 1
        input_img = input_img / 255.0
        input_img = input_img.transpose(2, 0, 1)
        input_tensor = input_img[np.newaxis, :, :, :].astype(np.float32)
        return input_tensor, ratio
    def inference(self, input_tensor):
        start = time.perf_counter()
        outputs = self.session.run(self.output_names, {self.input_names[0]: input_tensor})
        # print(f"Inference time: {(time.perf_counter() - start)*1000:.2f} ms")
        return outputs
    def process_output(self, output, ratio):
        predictions = np.squeeze(output[0]).T
        # Filter out object confidence scores below threshold
        scores = np.max(predictions[:, 4:], axis=1)
        predictions = predictions[scores > self.conf_threshold, :]
        scores = scores[scores > self.conf_threshold]
        if len(scores) == 0:
            return [], [], []
        # Get the class with the highest confidence
        class_ids = np.argmax(predictions[:, 4:], axis=1)
        # Get bounding boxes for each object
        boxes = self.extract_boxes(predictions, ratio)
        # Apply non-maxima suppression to suppress weak, overlapping bounding boxes
        indices = self.nms(boxes, scores, self.iou_threshold)
        return boxes[indices], scores[indices], class_ids[indices]
    def extract_boxes(self, predictions, ratio):
        # Extract boxes from predictions
        boxes = predictions[:, :4]
        # Scale boxes to original image dimensions
        # boxes = self.rescale_boxes(boxes)
        boxes *= ratio
        # Convert boxes to xyxy format
        boxes = self.xywh2xyxy(boxes)
        return boxes
    def rescale_boxes(self, boxes):
        # Rescale boxes to original image dimensions
        input_shape = np.array([self.input_width, self.input_height, self.input_width, self.input_height])
        boxes = np.divide(boxes, input_shape, dtype=np.float32)
        boxes *= np.array([self.img_width, self.img_height, self.img_width, self.img_height])
        return boxes
    def get_input_details(self):
        model_inputs = self.session.get_inputs()
        self.input_names = [model_inputs[i].name for i in range(len(model_inputs))]
        self.input_shape = model_inputs[0].shape
        self.input_height = self.input_shape[2]
        self.input_width = self.input_shape[3]
    def get_output_details(self):
        model_outputs = self.session.get_outputs()
        self.output_names = [model_outputs[i].name for i in range(len(model_outputs))]
    # ç­‰æ¯”例缩放图片
    def ratioresize(self, im, color=114):
        shape = im.shape[:2]
        new_h, new_w = self.input_height, self.input_width
        padded_img = np.ones((new_h, new_w, 3), dtype=np.uint8) * color
        # Scale ratio (new / old)
        r = min(new_h / shape[0], new_w / shape[1])
        # Compute padding
        new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
        if shape[::-1] != new_unpad:
            im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
        padded_img[: new_unpad[1], : new_unpad[0]] = im
        padded_img = np.ascontiguousarray(padded_img)
        return padded_img, 1 / r
    def nms(self, boxes, scores, iou_threshold):
        # Sort by score
        sorted_indices = np.argsort(scores)[::-1]
        keep_boxes = []
        while sorted_indices.size > 0:
            # Pick the last box
            box_id = sorted_indices[0]
            keep_boxes.append(box_id)
            # Compute IoU of the picked box with the rest
            ious = self.compute_iou(boxes[box_id, :], boxes[sorted_indices[1:], :])
            # Remove boxes with IoU over the threshold
            keep_indices = np.where(ious < iou_threshold)[0]
            # print(keep_indices.shape, sorted_indices.shape)
            sorted_indices = sorted_indices[keep_indices + 1]
        return keep_boxes
    def compute_iou(self, box, boxes):
        # Compute xmin, ymin, xmax, ymax for both boxes
        xmin = np.maximum(box[0], boxes[:, 0])
        ymin = np.maximum(box[1], boxes[:, 1])
        xmax = np.minimum(box[2], boxes[:, 2])
        ymax = np.minimum(box[3], boxes[:, 3])
        # Compute intersection area
        intersection_area = np.maximum(0, xmax - xmin) * np.maximum(0, ymax - ymin)
        # Compute union area
        box_area = (box[2] - box[0]) * (box[3] - box[1])
        boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
        union_area = box_area + boxes_area - intersection_area
        # Compute IoU
        iou = intersection_area / union_area
        return iou
    def xywh2xyxy(self, x):
        # Convert bounding box (x, y, w, h) to bounding box (x1, y1, x2, y2)
        y = np.copy(x)
        y[..., 0] = x[..., 0] - x[..., 2] / 2
        y[..., 1] = x[..., 1] - x[..., 3] / 2
        y[..., 2] = x[..., 0] + x[..., 2] / 2
        y[..., 3] = x[..., 1] + x[..., 3] / 2
        return y
if __name__ == "__main__":
    yolov8_detector = YOLOv8('model/detect/best.onnx', conf_thres=0.7, iou_thres=0.7)
    # æ‘„像头索引号,通常为0表示第一个摄像头
    camera_index = 0
    # æ‰“开摄像头
    cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
    # è®¾ç½®åˆ†è¾¨çއ
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)  # å®½åº¦
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)  # é«˜åº¦
    # æ£€æŸ¥æ‘„像头是否成功打开
    if not cap.isOpened():
        print("无法打开摄像头")
        exit()
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    print("摄像头分辨率:", width, "x", height)
    # ç›®æ ‡å›¾åƒå°ºå¯¸
    target_width = 1024
    target_height = 768
    # å¾ªçŽ¯è¯»å–æ‘„åƒå¤´ç”»é¢
    while True:
        ret, frame = cap.read()
        if not ret:
            print("无法读取摄像头画面")
            break
        # 1920*1080的图像,中心裁剪640*480的区域
        cropped_frame = frame[int(height / 2 - target_height / 2):int(height / 2 + target_height / 2),
                        int(width / 2 - target_width / 2):int(width / 2 + target_width / 2)]
        # è°ƒæ•´å›¾åƒå°ºå¯¸
        resized_frame = cv2.resize(cropped_frame, (target_width, target_height))
        boxes, scores, class_ids = yolov8_detector(resized_frame)
        print(boxes, scores, class_ids)
onnx-test.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,50 @@
import cv2
import numpy as np
import onnxruntime
from scipy.special import softmax
# åŠ è½½ONNX模型
session = onnxruntime.InferenceSession("model/classify/best.onnx")
# è¯»å–图片
img = cv2.imread("D:\\temp\\15.jpg")
# ä»Žres.json中读取类别
with open("res1-2.json", "r") as f:
    classes = eval(f.read())
# é¢„处理
blob = cv2.dnn.blobFromImage(img, 1/255.0, (640, 640), swapRB=True, crop=False)
# æ¨¡åž‹æŽ¨ç†
outputs = session.run(None, {session.get_inputs()[0].name: blob})
# print(outputs)
# åº”用softmax函数
probabilities = outputs[0]
# æ‰¾åˆ°æœ€å¤§æ¦‚率的类别
predicted_class = np.argmax(probabilities, axis=1)[0]
max_probability = np.max(probabilities, axis=1)[0]
# æ‰¾åˆ°æ¦‚率较高的前十个类别
top_ten_classes = np.argsort(probabilities, axis=1)[0][-5:]
# è¾“出前十个类别
print("Top 10 Classes:")
for i in top_ten_classes:
    print(f"{classes[i]}: {probabilities[0][i]}")
# åŽå¤„理
# for detection in outputs[0][0]:
#     confidence = detection[4]
#     if confidence > 0.5:
#         class_id = int(detection[5])
#         x, y, w, h = detection[:4]
#         cv2.rectangle(img, (int(x), int(y)), (int(x+w), int(y+h)), (0, 255, 0), 2)
#
# # æ˜¾ç¤ºç»“æžœ
# cv2.imshow("YOLOv8 Detection", img)
# cv2.waitKey(0)
onnx_predit.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,364 @@
import time
import cv2
import onnxruntime as ort
from PIL import Image
import numpy as np
# ç½®ä¿¡åº¦
confidence_thres = 0.35
# iou阈值
iou_thres = 0.5
# ç±»åˆ«
classes = {0: 'herb'}
# éšæœºé¢œè‰²
color_palette = np.random.uniform(100, 255, size=(len(classes), 3))
# åˆ¤æ–­æ˜¯ä½¿ç”¨GPU或CPU
providers = [
    ('CUDAExecutionProvider', {
        'device_id': 0,  # å¯ä»¥é€‰æ‹©GPU设备ID,如果你有多个GPU
    }),
    'CPUExecutionProvider',  # ä¹Ÿå¯ä»¥è®¾ç½®CPU作为备选
]
def calculate_iou(box, other_boxes):
    """
    è®¡ç®—给定边界框与一组其他边界框之间的交并比(IoU)。
    å‚数:
    - box: å•个边界框,格式为 [x1, y1, width, height]。
    - other_boxes: å…¶ä»–边界框的数组,每个边界框的格式也为 [x1, y1, width, height]。
    è¿”回值:
    - iou: ä¸€ä¸ªæ•°ç»„,包含给定边界框与每个其他边界框的IoU值。
    """
    # è®¡ç®—交集的左上角坐标
    x1 = np.maximum(box[0], np.array(other_boxes)[:, 0])
    y1 = np.maximum(box[1], np.array(other_boxes)[:, 1])
    # è®¡ç®—交集的右下角坐标
    x2 = np.minimum(box[0] + box[2], np.array(other_boxes)[:, 0] + np.array(other_boxes)[:, 2])
    y2 = np.minimum(box[1] + box[3], np.array(other_boxes)[:, 1] + np.array(other_boxes)[:, 3])
    # è®¡ç®—交集区域的面积
    intersection_area = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1)
    # è®¡ç®—给定边界框的面积
    box_area = box[2] * box[3]
    # è®¡ç®—其他边界框的面积
    other_boxes_area = np.array(other_boxes)[:, 2] * np.array(other_boxes)[:, 3]
    # è®¡ç®—IoU值
    iou = intersection_area / (box_area + other_boxes_area - intersection_area)
    return iou
def custom_NMSBoxes(boxes, scores, confidence_threshold, iou_threshold):
    # å¦‚果没有边界框,则直接返回空列表
    if len(boxes) == 0:
        return []
    # å°†å¾—分和边界框转换为NumPy数组
    scores = np.array(scores)
    boxes = np.array(boxes)
    # æ ¹æ®ç½®ä¿¡åº¦é˜ˆå€¼è¿‡æ»¤è¾¹ç•Œæ¡†
    mask = scores > confidence_threshold
    filtered_boxes = boxes[mask]
    filtered_scores = scores[mask]
    # å¦‚果过滤后没有边界框,则返回空列表
    if len(filtered_boxes) == 0:
        return []
    # æ ¹æ®ç½®ä¿¡åº¦å¾—分对边界框进行排序
    sorted_indices = np.argsort(filtered_scores)[::-1]
    # åˆå§‹åŒ–一个空列表来存储选择的边界框索引
    indices = []
    # å½“还有未处理的边界框时,循环继续
    while len(sorted_indices) > 0:
        # é€‰æ‹©å¾—分最高的边界框索引
        current_index = sorted_indices[0]
        indices.append(current_index)
        # å¦‚果只剩一个边界框,则结束循环
        if len(sorted_indices) == 1:
            break
        # èŽ·å–å½“å‰è¾¹ç•Œæ¡†å’Œå…¶ä»–è¾¹ç•Œæ¡†
        current_box = filtered_boxes[current_index]
        other_boxes = filtered_boxes[sorted_indices[1:]]
        # è®¡ç®—当前边界框与其他边界框的IoU
        iou = calculate_iou(current_box, other_boxes)
        # æ‰¾åˆ°IoU低于阈值的边界框,即与当前边界框不重叠的边界框
        non_overlapping_indices = np.where(iou <= iou_threshold)[0]
        # æ›´æ–°sorted_indices以仅包含不重叠的边界框
        sorted_indices = sorted_indices[non_overlapping_indices + 1]
    # è¿”回选择的边界框索引
    return indices
def draw_detections(img, box, score, class_id):
    """
    åœ¨è¾“入图像上绘制检测到的对象的边界框和标签。
    å‚æ•°:
            img: è¦åœ¨å…¶ä¸Šç»˜åˆ¶æ£€æµ‹ç»“果的输入图像。
            box: æ£€æµ‹åˆ°çš„边界框。
            score: å¯¹åº”的检测得分。
            class_id: æ£€æµ‹åˆ°çš„对象的类别ID。
    è¿”回:
            æ— 
    """
    # æå–边界框的坐标
    x1, y1, w, h = box
    # æ ¹æ®ç±»åˆ«ID检索颜色
    color = color_palette[class_id]
    # åœ¨å›¾åƒä¸Šç»˜åˆ¶è¾¹ç•Œæ¡†
    cv2.rectangle(img, (int(x1), int(y1)), (int(x1 + w), int(y1 + h)), color, 2)
    # åˆ›å»ºæ ‡ç­¾æ–‡æœ¬ï¼ŒåŒ…括类名和得分
    label = f'{classes[class_id]}: {score:.2f}'
    # è®¡ç®—标签文本的尺寸
    (label_width, label_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
    # è®¡ç®—标签文本的位置
    label_x = x1
    label_y = y1 - 10 if y1 - 10 > label_height else y1 + 10
    # ç»˜åˆ¶å¡«å……的矩形作为标签文本的背景
    cv2.rectangle(img, (label_x, label_y - label_height), (label_x + label_width, label_y + label_height), color, cv2.FILLED)
    # åœ¨å›¾åƒä¸Šç»˜åˆ¶æ ‡ç­¾æ–‡æœ¬
    cv2.putText(img, label, (label_x, label_y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
def preprocess(img, input_width, input_height):
    """
    åœ¨æ‰§è¡ŒæŽ¨ç†ä¹‹å‰é¢„处理输入图像。
    è¿”回:
        image_data: ä¸ºæŽ¨ç†å‡†å¤‡å¥½çš„预处理后的图像数据。
    """
    # èŽ·å–è¾“å…¥å›¾åƒçš„é«˜åº¦å’Œå®½åº¦
    img_height, img_width = img.shape[:2]
    # å°†å›¾åƒé¢œè‰²ç©ºé—´ä»ŽBGR转换为RGB
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # å°†å›¾åƒå¤§å°è°ƒæ•´ä¸ºåŒ¹é…è¾“入形状
    img = cv2.resize(img, (input_width, input_height))
    # é€šè¿‡é™¤ä»¥255.0来归一化图像数据
    image_data = np.array(img) / 255.0
    # è½¬ç½®å›¾åƒï¼Œä½¿é€šé“维度为第一维
    image_data = np.transpose(image_data, (2, 0, 1))  # é€šé“首
    # æ‰©å±•图像数据的维度以匹配预期的输入形状
    image_data = np.expand_dims(image_data, axis=0).astype(np.float32)
    # è¿”回预处理后的图像数据
    return image_data, img_height, img_width
def postprocess(input_image, output, input_width, input_height, img_width, img_height):
    """
    å¯¹æ¨¡åž‹è¾“出进行后处理,提取边界框、得分和类别ID。
    å‚æ•°:
        input_image (numpy.ndarray): è¾“入图像。
        output (numpy.ndarray): æ¨¡åž‹çš„输出。
        input_width (int): æ¨¡åž‹è¾“入宽度。
        input_height (int): æ¨¡åž‹è¾“入高度。
        img_width (int): åŽŸå§‹å›¾åƒå®½åº¦ã€‚
        img_height (int): åŽŸå§‹å›¾åƒé«˜åº¦ã€‚
    è¿”回:
        numpy.ndarray: ç»˜åˆ¶äº†æ£€æµ‹ç»“果的输入图像。
    """
    # è½¬ç½®å’ŒåŽ‹ç¼©è¾“å‡ºä»¥åŒ¹é…é¢„æœŸçš„å½¢çŠ¶
    outputs = np.transpose(np.squeeze(output[0]))
    # èŽ·å–è¾“å‡ºæ•°ç»„çš„è¡Œæ•°
    rows = outputs.shape[0]
    # ç”¨äºŽå­˜å‚¨æ£€æµ‹çš„边界框、得分和类别ID的列表
    boxes = []
    scores = []
    class_ids = []
    # è®¡ç®—边界框坐标的缩放因子
    x_factor = img_width / input_width
    y_factor = img_height / input_height
    # éåŽ†è¾“å‡ºæ•°ç»„çš„æ¯ä¸€è¡Œ
    for i in range(rows):
        # ä»Žå½“前行提取类别得分
        classes_scores = outputs[i][4:]
        # æ‰¾åˆ°ç±»åˆ«å¾—分中的最大得分
        max_score = np.amax(classes_scores)
        # å¦‚果最大得分高于置信度阈值
        if max_score >= confidence_thres:
            # èŽ·å–å¾—åˆ†æœ€é«˜çš„ç±»åˆ«ID
            class_id = np.argmax(classes_scores)
            # ä»Žå½“前行提取边界框坐标
            x, y, w, h = outputs[i][0], outputs[i][1], outputs[i][2], outputs[i][3]
            # è®¡ç®—边界框的缩放坐标
            left = int((x - w / 2) * x_factor)
            top = int((y - h / 2) * y_factor)
            width = int(w * x_factor)
            height = int(h * y_factor)
            # å°†ç±»åˆ«ID、得分和框坐标添加到各自的列表中
            class_ids.append(class_id)
            scores.append(max_score)
            boxes.append([left, top, width, height])
    # åº”用非最大抑制过滤重叠的边界框
    indices = custom_NMSBoxes(boxes, scores, confidence_thres, iou_thres)
    # éåŽ†éžæœ€å¤§æŠ‘åˆ¶åŽçš„é€‰å®šç´¢å¼•
    for i in indices:
        # æ ¹æ®ç´¢å¼•获取框、得分和类别ID
        box = boxes[i]
        score = scores[i]
        class_id = class_ids[i]
        # åœ¨è¾“入图像上绘制检测结果
        draw_detections(input_image, box, score, class_id)
    # è¿”回修改后的输入图像
    return input_image
def init_detect_model(model_path):
    # ä½¿ç”¨ONNX模型文件创建一个推理会话,并指定执行提供者
    session = ort.InferenceSession(model_path, providers=providers)
    # èŽ·å–æ¨¡åž‹çš„è¾“å…¥ä¿¡æ¯
    model_inputs = session.get_inputs()
    # èŽ·å–è¾“å…¥çš„å½¢çŠ¶ï¼Œç”¨äºŽåŽç»­ä½¿ç”¨
    input_shape = model_inputs[0].shape
    # ä»Žè¾“入形状中提取输入宽度
    input_width = input_shape[2]
    # ä»Žè¾“入形状中提取输入高度
    input_height = input_shape[3]
    # è¿”回会话、模型输入信息、输入宽度和输入高度
    return session, model_inputs, input_width, input_height
def detect_object(image, session, model_inputs, input_width, input_height):
    # å¦‚果输入的图像是PIL图像对象,将其转换为NumPy数组
    if isinstance(image, Image.Image):
        result_image = np.array(image)
    else:
        # å¦åˆ™ï¼Œç›´æŽ¥ä½¿ç”¨è¾“入的图像(假定已经是NumPy数组)
        result_image = image
    # é¢„处理图像数据,调整图像大小并可能进行归一化等操作
    img_data, img_height, img_width = preprocess(result_image, input_width, input_height)
    # ä½¿ç”¨é¢„处理后的图像数据进行推理
    outputs = session.run(None, {model_inputs[0].name: img_data})
    # å¯¹æŽ¨ç†ç»“果进行后处理,例如解码检测框,过滤低置信度的检测等
    output_image = postprocess(result_image, outputs, input_width, input_height, img_width, img_height)
    # è¿”回处理后的图像
    return output_image
if __name__ == '__main__':
    # æ¨¡åž‹æ–‡ä»¶çš„路径
    model_path = 'model/detect/best.onnx'
    # åˆå§‹åŒ–检测模型,加载模型并获取模型输入节点信息和输入图像的宽度、高度
    session, model_inputs, input_width, input_height = init_detect_model(model_path)
    # ä¸‰ç§æ¨¡å¼ 1为图片预测,并显示结果图片;2为摄像头检测,并实时显示FPS; 3为视频检测,并保存结果视频
    mode = 2
    if mode == 1:
        # è¯»å–图像文件
        image_data = cv2.imread("street.jpg")
        # ä½¿ç”¨æ£€æµ‹æ¨¡åž‹å¯¹è¯»å…¥çš„图像进行对象检测
        result_image = detect_object(image_data, session, model_inputs, input_width, input_height)
        # å°†æ£€æµ‹åŽçš„图像保存到文件
        cv2.imwrite("output_image.jpg", result_image)
        # åœ¨çª—口中显示检测后的图像
        cv2.imshow('Output', result_image)
        # ç­‰å¾…用户按键,然后关闭显示窗口
        cv2.waitKey(0)
    elif mode == 2:
        # æ‘„像头索引号,通常为0表示第一个摄像头
        camera_index = 0
        # æ‰“开摄像头
        cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
        # è®¾ç½®åˆ†è¾¨çއ
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)  # å®½åº¦
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)  # é«˜åº¦
        # æ£€æŸ¥æ‘„像头是否成功打开
        if not cap.isOpened():
            print("无法打开摄像头")
            exit()
        width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
        height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
        print("摄像头分辨率:", width, "x", height)
        # åˆå§‹åŒ–帧数计数器和起始时间
        frame_count = 0
        start_time = time.time()
        # ç›®æ ‡å›¾åƒå°ºå¯¸
        target_width = 1024
        target_height = 768
        # å¾ªçŽ¯è¯»å–æ‘„åƒå¤´è§†é¢‘æµ
        while True:
            # è¯»å–一帧
            ret, frame = cap.read()
            # æ£€æŸ¥å¸§æ˜¯å¦æˆåŠŸè¯»å–
            if not ret:
                print("Error: Could not read frame.")
                break
            # 1920*1080的图像,中心裁剪640*480的区域
            cropped_frame = frame[int(height / 2 - target_height / 2):int(height / 2 + target_height / 2),
                                int(width / 2 - target_width / 2):int(width / 2 + target_width / 2)]
            # è°ƒæ•´å›¾åƒå°ºå¯¸
            resized_frame = cv2.resize(cropped_frame, (target_width, target_height))
            # ä½¿ç”¨æ£€æµ‹æ¨¡åž‹å¯¹è¯»å…¥çš„帧进行对象检测
            output_image = detect_object(resized_frame, session, model_inputs, input_width, input_height)
            # è®¡ç®—帧速率
            frame_count += 1
            end_time = time.time()
            elapsed_time = end_time - start_time
            fps = frame_count / elapsed_time
            print(f"FPS: {fps:.2f}")
            # å°†FPS绘制在图像上
            cv2.putText(output_image, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
            # åœ¨çª—口中显示当前帧
            cv2.imshow("Video", output_image)
            # æŒ‰ä¸‹ 'q' é”®é€€å‡ºå¾ªçޝ
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        # é‡Šæ”¾æ‘„像头资源
        cap.release()
        # å…³é—­çª—口
        cv2.destroyAllWindows()
    elif mode == 3:
        # è¾“入视频路径
        input_video_path = 'kun.mp4'
        # è¾“出视频路径
        output_video_path = 'kun_det.mp4'
        # æ‰“开视频文件
        cap = cv2.VideoCapture(input_video_path)
        # æ£€æŸ¥è§†é¢‘是否成功打开
        if not cap.isOpened():
            print("Error: Could not open video.")
            exit()
        # è¯»å–视频的基本信息
        frame_width = int(cap.get(3))
        frame_height = int(cap.get(4))
        fps = cap.get(cv2.CAP_PROP_FPS)
        # å®šä¹‰è§†é¢‘编码器和创建VideoWriter对象
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # æ ¹æ®æ–‡ä»¶ååŽç¼€ä½¿ç”¨åˆé€‚的编码器
        out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))
        # åˆå§‹åŒ–帧数计数器和起始时间
        frame_count = 0
        start_time = time.time()
        while True:
            ret, frame = cap.read()
            if not ret:
                print("Info: End of video file.")
                break
            # å¯¹è¯»å…¥çš„帧进行对象检测
            output_image = detect_object(frame, session, model_inputs, input_width, input_height)
            # è®¡ç®—并打印帧速率
            frame_count += 1
            end_time = time.time()
            elapsed_time = end_time - start_time
            if elapsed_time > 0:
                fps = frame_count / elapsed_time
                print(f"FPS: {fps:.2f}")
            # å°†å¤„理后的帧写入输出视频
            out.write(output_image)
            #(可选)实时显示处理后的视频帧
            cv2.imshow("Output Video", output_image)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        # é‡Šæ”¾èµ„源
        cap.release()
        out.release()
        cv2.destroyAllWindows()
    else:
        print("输入错误,请检查mode的赋值")
pachong.py
@@ -1,13 +1,20 @@
import concurrent.futures
import os
import time
import requests
import re
def imgdata_set(save_path, word, epoch):
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    else:
        return 0
    q = 0     # åœæ­¢çˆ¬å–图片条件
    a = 0     # å›¾ç‰‡åç§°
    while(True):
        time.sleep(1)
        print("开始爬取图片")
        url = "https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={}&pn={}&ct=&ic=0&lm=-1&width=0&height=0".format(word, q)
        # word=需要搜索的名字
        headers = {
@@ -16,21 +23,28 @@
        response = requests.get(url, headers=headers)  # å‘送请求获取响应
        html = response.text  # èŽ·å–å“åº”çš„HTML内容
        urls = re.findall('"objURL":"(.*?)"', html)  # ä½¿ç”¨æ­£åˆ™è¡¨è¾¾å¼æå–图片URL
        for url in urls:
            try:
                print(a)  # å›¾ç‰‡çš„名字
                response = requests.get(url, headers=headers)  # å‘送请求获取图片响应E:\yaocai\juhua
                image = response.content  # èŽ·å–å›¾ç‰‡å†…å®¹
                with open(os.path.join(save_path, "{}.jpg".format(a)), 'wb') as f:  # å°†å›¾ç‰‡å†…容保存到指定路径
                    f.write(image)
                a = a + 1
            except Exception as e:
                pass
            continue
        print(len(urls))
        # ä½¿ç”¨concurrent.futures实现并发下载
        with concurrent.futures.ThreadPoolExecutor( max_workers=10) as executor:
            # æäº¤æ‰€æœ‰ä¸‹è½½ä»»åŠ¡å¹¶æ”¶é›†future对象
            futures = [executor.submit(download_image, index, headers,save_path,url ) for index,url in enumerate(urls)]
        q = q + 20
        if (q / 20) >= int(epoch):
            break
def download_image(a, headers, save_path, url):
        try:
            print(a)  # å›¾ç‰‡çš„名字
            response = requests.get(url, headers=headers, timeout=10)  # å‘送请求获取图片响应
            # å¦‚果没有一直响应怎么处理
            image = response.content  # èŽ·å–å›¾ç‰‡å†…å®¹
            with open(os.path.join(save_path, "{}.jpg".format(a)), 'wb') as f:  # å°†å›¾ç‰‡å†…容保存到指定路径
                f.write(image)
        except Exception as e:
            pass
if __name__ == "__main__":
    save_path = input('你想保存的路径:')  # è¯¢é—®ç”¨æˆ·ä¿å­˜è·¯å¾„
    word = input('你想要下载什么图片?请输入:')  # è¯¢é—®ç”¨æˆ·æœç´¢å…³é”®è¯
paherbbaidu.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,46 @@
import mysql.connector
from mysql.connector import Error
from pachong import imgdata_set
from quchong import quchongmethod
import shutil
# è¿žæŽ¥mysql æŸ¥è¯¢æ•°æ®åº“
def mysql_connect():
    try:
        conn = mysql.connector.connect(host='localhost',
                                       database='herb',
                                       user='root',
                                       password='123456')
        if conn.is_connected():
            print('Connected to MySQL database')
            return conn
    except Error as e:
        print(e)
# æŸ¥è¯¢dry_herb_info表
def mysql_select(conn):
    cursor = conn.cursor()
    sql = "SELECT name, pinyin FROM dry_herb_info where pinyin is not null and pinyin <> ''"
    cursor.execute(sql)
    result = cursor.fetchall()
    return result
# main
if __name__ == '__main__':
    conn = mysql_connect()
    result = mysql_select(conn)
    for row in result:
        name = row[0]
        pinyin = row[1]
        print(name)
        print(pinyin)
        imgdata_set('E:/pachong/'+pinyin, name + '饮片', 2)
        quchongmethod('E:/pachong/'+pinyin, 'E:/pachong/2/'+pinyin)
        #删除临时文件夹
        shutil.rmtree('E:/pachong/2/'+pinyin)
pc.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,35 @@
import os
import requests
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO
def fetch_images(keyword, save_path):
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    url = f"https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={keyword}"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    img_tags = soup.find_all('ObjURL', class_='obj')
    for i, img_tag in enumerate(img_tags):
        try:
            img_url = img_tag['data-src']
            img_data = requests.get(img_url).content
            img = Image.open(BytesIO(img_data))
            img.save(os.path.join(save_path, f"{keyword}_{i}.jpg"))
            print(f"Downloaded {keyword}_{i}.jpg")
        except Exception as e:
            print(f"Failed to download image: {e}")
if __name__ == "__main__":
    keyword = "人参"
    save_path = "images"
    fetch_images(keyword, save_path)
quchong.py
@@ -52,12 +52,9 @@
                result = "两张图相同"
    return result
if __name__ == '__main__':
    load_path = 'E:\yaocai\yinyanghuo'  # è¦åŽ»é‡çš„æ–‡ä»¶å¤¹
    save_path = 'E:\yaocai\\2\\yinyanghuo'  # ç©ºæ–‡ä»¶å¤¹ï¼Œç”¨äºŽå­˜å‚¨æ£€æµ‹åˆ°çš„重复的照片
def quchongmethod(load_path, save_path):
    os.makedirs(save_path, exist_ok=True)
    # èŽ·å–å›¾ç‰‡åˆ—è¡¨ file_map,字典{文件路径filename : æ–‡ä»¶å¤§å°image_size}
    file_map = {}
    image_size = 0
@@ -70,13 +67,11 @@
            # print('the full name of the file is %s' % os.path.join(parent, filename))
            image_size = os.path.getsize(os.path.join(parent, filename))
            file_map.setdefault(os.path.join(parent, filename), image_size)
    # èŽ·å–çš„å›¾ç‰‡åˆ—è¡¨æŒ‰ æ–‡ä»¶å¤§å°image_size æŽ’序
    file_map = sorted(file_map.items(), key=lambda d: d[1], reverse=False)
    file_list = []
    for filename, image_size in file_map:
        file_list.append(filename)
    # å–出重复的图片
    file_repeat = []
    for currIndex, filename in enumerate(file_list):
@@ -101,8 +96,14 @@
        currIndex += 1
        if currIndex >= (len(file_list)-2):
            break
    # å°†é‡å¤çš„图片移动到新的文件夹,实现对原文件夹降重
    for image in file_repeat:
        shutil.move(image, save_path)
        print("正在移除重复照片:", image)
if __name__ == '__main__':
    load_path = 'E:\yaocai\\chenpi'  # è¦åŽ»é‡çš„æ–‡ä»¶å¤¹
    save_path = 'E:\yaocai\\2\\chenpi'  # ç©ºæ–‡ä»¶å¤¹ï¼Œç”¨äºŽå­˜å‚¨æ£€æµ‹åˆ°çš„重复的照片
    quchongmethod(load_path,save_path)
replaceLabelNumber.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,38 @@
import os
def process_file(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
    with open(file_path, 'w') as file:
        for line in lines:
            # å°è¯•从每一行中提取第一个数字
            try:
                number = int(line.split()[0])
            except ValueError:
                # å¦‚果提取失败,跳过当前行
                file.write(line)
                continue
            new_number = number + 1
            # æ›¿æ¢åŽŸå§‹è¡Œä¸­çš„ç¬¬ä¸€ä¸ªæ•°å­—
            updated_line = line.replace(str(number), str(new_number), 1)
            # å†™å…¥æ›´æ–°åŽçš„行
            file.write(updated_line)
if __name__ == "__main__":
    # æŒ‡å®šç›®å½•
    target_directory = 'E:\\herb_scan.v1i.yolov8\\valid\\labels'
    # èŽ·å–ç›®å½•ä¸‹çš„æ‰€æœ‰txt文件
    txt_files = [file for file in os.listdir(target_directory) if file.endswith('.txt')]
    # å¤„理每个文件
    for txt_file in txt_files:
        file_path = os.path.join(target_directory, txt_file)
        process_file(file_path)
    print("处理完成!")
save_img.py
@@ -6,12 +6,17 @@
# æ‰“开摄像头
cap = cv2.VideoCapture(camera_index)
# è®¾ç½®åˆ†è¾¨çއ
# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)  # å®½åº¦
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)  # é«˜åº¦
# æ£€æŸ¥æ‘„像头是否成功打开
if not cap.isOpened():
    print("无法打开摄像头")
    exit()
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print("摄像头分辨率:", width, "x", height)
# å›¾ç‰‡ä¿å­˜è·¯å¾„
save_path = "captured_images/"
@@ -36,6 +41,8 @@
        print("无法读取摄像头画面")
        break
# è£å‰ªå›¾åƒ
#     cropped_frame = frame[750:1230, 1650:2290]
    # è°ƒæ•´å›¾åƒå°ºå¯¸
    resized_frame = cv2.resize(frame, (target_width, target_height))
@@ -43,20 +50,20 @@
    current_time = time.time()
    # å¦‚果距离上一次保存已经过去1秒,则保存当前画面
    if current_time - start_time >= 1.0:
        # ç”Ÿæˆä¿å­˜æ–‡ä»¶åï¼Œä»¥å½“前时间命名
        save_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".jpg"
        # ä¿å­˜è°ƒæ•´å°ºå¯¸åŽçš„图片
        cv2.imwrite(save_path + save_name, resized_frame)
        print("保存图片:", save_name)
        # é‡ç½®è®¡æ—¶å™¨
        start_time = time.time()
    # if current_time - start_time >= 3.0:
    #     # ç”Ÿæˆä¿å­˜æ–‡ä»¶åï¼Œä»¥å½“前时间命名
    #     save_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".jpg"
    #     # ä¿å­˜è°ƒæ•´å°ºå¯¸åŽçš„图片
    #     cv2.imwrite(save_path + save_name, frame)
    #     print("保存图片:", save_name)
    #     # é‡ç½®è®¡æ—¶å™¨
    #     start_time = time.time()
    # æ˜¾ç¤ºç”»é¢
    cv2.imshow("Camera", resized_frame)
    cv2.imshow("Camera", frame)
    # æ£€æµ‹æŒ‰é”®ï¼Œå¦‚果按下q键则退出循环
    if cv2.waitKey(1000) & 0xFF == ord('q'):
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# å…³é—­æ‘„像头
shot_onnx.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,105 @@
import cv2
import time
import numpy as np
import onnxruntime
from scipy.special import softmax
# åŠ è½½ONNX模型
session = onnxruntime.InferenceSession("model/detect/best.onnx")
# æ‘„像头索引号,通常为0表示第一个摄像头
camera_index = 0
# æ‰“开摄像头
cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
# è®¾ç½®åˆ†è¾¨çއ
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)  # å®½åº¦
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)  # é«˜åº¦
# æ£€æŸ¥æ‘„像头是否成功打开
if not cap.isOpened():
    print("无法打开摄像头")
    exit()
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print("摄像头分辨率:", width, "x", height)
# ä»Žres.json中读取类别
# with open("res1-2.json", "r") as f:
#     classes = eval(f.read())
# ç›®æ ‡å›¾åƒå°ºå¯¸
target_width = 1024
target_height = 768
# è®¡æ—¶å™¨
start_time = time.time()
# å¾ªçŽ¯è¯»å–æ‘„åƒå¤´ç”»é¢
while True:
    ret, frame = cap.read()
    if not ret:
        print("无法读取摄像头画面")
        break
    # 1920*1080的图像,中心裁剪640*480的区域
    cropped_frame = frame[int(height / 2 - target_height / 2):int(height / 2 + target_height / 2),
                    int(width / 2 - target_width / 2):int(width / 2 + target_width / 2)]
    # è°ƒæ•´å›¾åƒå°ºå¯¸
    resized_frame = cv2.resize(cropped_frame, (target_width, target_height))
    # èŽ·å–å½“å‰æ—¶é—´
    current_time = time.time()
    #如果距离上一次保存已经过去1秒,则保存当前画面
    # if current_time - start_time >= 3.0:
    #     # ç”Ÿæˆä¿å­˜æ–‡ä»¶åï¼Œä»¥å½“前时间命名
    #     save_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".jpg"
    #     # ä¿å­˜è°ƒæ•´å°ºå¯¸åŽçš„图片
    #     cv2.imwrite(save_path + save_name, frame)
    #     print("保存图片:", save_name)
    #     # é‡ç½®è®¡æ—¶å™¨
    #     start_time = time.time()
    # é¢„处理
    blob = cv2.dnn.blobFromImage(resized_frame, 1 / 255.0, (640, 640), swapRB=True, crop=False)
    # æ¨¡åž‹æŽ¨ç†
    outputs = session.run(None, {session.get_inputs()[0].name: blob})
    output = np.transpose(np.squeeze(outputs[0]));
    rows = output.shape[0]
    boxes = []
    scores = []
    class_ids = []
    for i in range(rows):
        classes_scores = output[i][4:]
        max_score = np.amax(classes_scores)
        if max_score > 0.5:
            classid = np.argmax(classes_scores)
            scores.append(max_score)
            class_ids.append(classid)
    print(class_ids)
    print(scores)
    # # è¾“出前十个类别
    # print("Top 5 Classes:")
    # for i in top_ten_classes:
    #     print(f"{classes[i]}: {probabilities[0][i]}")
    # æ˜¾ç¤ºç”»é¢
    cv2.imshow("Camera", resized_frame)
    # æ£€æµ‹æŒ‰é”®ï¼Œå¦‚果按下q键则退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# å…³é—­æ‘„像头
cap.release()
# å…³é—­æ‰€æœ‰çª—口
cv2.destroyAllWindows()
speech/deepSpeechTest.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,20 @@
from deepspeech import Model
import scipy.io.wavfile as wav
import numpy as np
# æŒ‡å®šæ¨¡åž‹å’Œè¯„分器文件路径
model_path = 'model/deepspeech-0.9.3-models-zh-CN.pbmm'
scorer_path = 'model/deepspeech-0.9.3-models-zh-CN.scorer'
# åˆå§‹åŒ–DeepSpeech模型
ds = Model(model_path)
ds.enableExternalScorer(scorer_path)
# åŠ è½½éŸ³é¢‘æ–‡ä»¶
audio_path = 'audio/input.wav'
fs, audio = wav.read(audio_path)
# è¿›è¡Œè¯­éŸ³è½¬æ–‡å­—
text = ds.stt(audio)
print('Transcribed text:', text)
speech/formatmp3.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,5 @@
from pydub import AudioSegment
# åŠ è½½mp3文件
mp3_audio = AudioSegment.from_mp3("input.mp3")
speech/whisper2.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1 @@
from faster import WhisperModel
speech/whisperTest.py
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,10 @@
import whisper
model = whisper.load_model("medium")
result = model.transcribe("audio/input.wav")
print(result["text"])
# tiny 72.1M æˆ‘说问大家这个话里给放在前台了是卡罗前台是吗对好的谢谢
# base 1XXM  æˆ‘帅哥那个发力给他放在前台了是7号了前台是吧对好的谢谢好
# small 461M  å–‚你好哦我順風的一個畫地給放在前台了是7號樓前台是吧對好的謝謝
# medium 1.42G  å–‚你好你好我身后那儿有个法律给放在前台了是7号楼前台是吧对好的谢谢好