使opencv视频捕捉速度更快

2024-04-06

所以我创建了一个神经网络(CNN),可以使用 opencv 实时预测一个人的性别,一切都很完美,但是,当我运行 OpenCv 代码时有很多滞后,我的网络摄像头还不错,这里是我的代码

    '''
Real-time Face Gender Recognition using Conv-Nueral Network (CNN) and Cv2

Here we predict the save model that it is train
'''
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import os
import cvlib as cv
import imutils

# load the model
model = load_model('gender_detection.model')

# open webcams and initiate the camara
webcam = cv2.VideoCapture(0, cv2.CAP_DSHOW)

classes = ['hombre', 'mujer']

# loop through frames
while webcam.isOpened():
    # read frame from webcam
    status, frame = webcam.read()
    #webcam.set(cv2.CAP_PROP_FPS, 1000)
    frame = cv2.flip(frame, 1)

    # apply face detection
    face, confidence = cv.detect_face(frame) # this detects that there is a face in the camara, cvlib does, but not if it is a man that detects the neural network

    # loop through detected faces
    for idx, f in enumerate(face):
        # get corner points of face rectangle
        # this only will draw a rectangle when the cvlib detects the face with the vars giving up there
        startX, startY = f[0], f[1]
        endX, endY = f[2], f[3]

        # draw the rectangle over the face
        cv2.rectangle(frame, (startX, startY), (endX, endY), (0,255,0), 2)

        # crop the detected face region
        face_crop = np.copy(frame[startY:endY, startX:endX])

        if face_crop.shape[0] < 10 or face_crop.shape[1] < 10:
            continue

        # preprocessing for gender detection model
        face_crop = cv2.resize(face_crop, (96,96))
        face_crop = face_crop.astype("float") / 255.0
        face_crop = img_to_array(face_crop)
        face_crop = np.expand_dims(face_crop, axis=0)

        # apply gender detection face with the model
        conf = model.predict(face_crop)[0]

        # get label with max acc
        idx = np.argmax(conf)
        label = classes[idx]

        label = "{}: {:.2f}".format(label, conf[idx] * 100)

        Y = startY - 10 if startY - 10 > 10 else startY + 10

        # write label and confidence above the face rectangle
        cv2.putText(frame, label, (startX, Y), cv2.FONT_HERSHEY_SIMPLEX,
                    0.7, (0,255,0), 2)

    # display output
    cv2.imshow("Gender Detection", frame)

    # press "Q" to stop
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


#realese resources
webcam.release()
cv2.destroyAllWindows()

我也尝试使用 cv2.CAP_PROB_FPS 但这只能有一点帮助,没有多大帮助。


我在使用 openCV 视频捕获和文本检测时遇到了同样的问题。这不是网络摄像头的质量问题,而是 openCV 向您显示帧的速度只能与您在性别检测中处理帧的速度一样快。对我有用的解决方案是使用多线程。

您可以创建一个用于 OpenCV 视频捕获的线程,然后创建另一个用于图像处理的线程。警告:如果不更改图像处理本身,您无法神奇地使图像处理更快。需要多久就需要多久。您可以做的是允许 openCV 自行工作并将帧发送到交换类,然后允许图像处理抓取帧并按照自己的节奏工作,而 CV2 继续正常进行。

这是我的 OCR 图像处理类的(缩短的)版本。您可以看到,在 start() 中我正在创建一个指向 ocr() 进程的线程。这就是您的性别识别过程可以进行的地方。

class OCR:

    # def __init__(self, exchange: VideoStream, language=None):
    def __init__(self):
        self.exchange = None
        # init stuff for OCR not relevant to my example, but note that it 
        # takes a VideoStream class called exchange which is where this class 
        # grabs frames to process

    def start(self):
        Thread(target=self.ocr, args=()).start()
        return self

    def set_exchange(self, video_stream):
        self.exchange = video_stream

    def ocr(self):

        while not self.stopped:
            if self.exchange is not None:
                frame = self.exchange.frame

                # # # OCR stuff goes here

现在,VideoStream 类在不同的线程中按照自己的节奏抓取帧。然后,图像处理类 (OCR) 可以按照自己的节奏获取这些帧,并且两者不会影响彼此的性能。

class VideoStream:
    """Class for CV2 video capture. The start() method will create a new 
thread to read the video stream"""
    def __init__(self, src=0):
        self.stream = cv2.VideoCapture(src)
        (self.grabbed, self.frame) = self.stream.read()
        # self._boxes = None
        self.stopped = False

    def start(self):
        Thread(target=self.get, args=()).start()
        return self

    def get(self):
        while not self.stopped:
            (self.grabbed, self.frame) = self.stream.read()

    def get_video_dimensions(self):
        width = self.stream.get(cv2.CAP_PROP_FRAME_WIDTH)
        height = self.stream.get(cv2.CAP_PROP_FRAME_HEIGHT)
        return int(width), int(height)

    def stop_process(self):
        self.stopped = True

然后您可以像平常一样执行 CV2 imshow 循环。

exchange = VideoStream(0).start()
ocr = OCR().start()
ocr.set_exchange(exchange)

 while True:  # Begins a loop for the real-time OCR display
        pressed_key = cv2.waitKey(1) & 0xFF
        if pressed_key == ord('q'):
            stop_stream_ocr(exchange, ocr)
            break

        frame = exchange.frame 

        cv2.imshow("Video Get Frame", frame)
        cps1.increment()

请注意,您无法真正控制 CV2 决定在其内部工作中使用什么线程,但这种方法将允许您以其自然的 fps 显示网络摄像头,同时图像处理在后台进行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使opencv视频捕捉速度更快 的相关文章

  • 不能在jinja2宏中使用current_user?

    我使用 Flask Login 它提供了current user模板中的对象 我想编写一个宏来显示评论表单或登录链接 具体取决于用户是否登录 如果我直接在模板中使用此代码 它会起作用 if current user is authentic
  • 无法使用 beautifulsoup 模块 python 从 HTML 检索温度值

    我正在使用 BeautifulSoup4 来解析此 HTML 查看源代码 https weather com en IN weather today l 17 39 78 49 https weather com en IN weather
  • 如何使用 python 从嵌套表结构中识别最终父级?

    我有下表 我的问题是 我如何以编程方式识别最终父级 以下是通过示例解释的规则 the id 5 0的父母是51 0 身份证号51 0没有父母 因此 id5 0的最终父级是51 0 the id 6 0的父母是1 0 身份证号1 0的父母是1
  • pandas python 根据一个或多个其他列的子集更新 A 列的子集

    Edit我修改了下面的部分描述 以澄清 功能 和 组 的含义 修复拼写错误 并包含我尝试过的其他代码 我的熊猫df有 450 万行和 23 列 下表显示了几行df2这是从生成的df 它显示了两组 eeskin and hduquant 和三
  • PyQt4 信号和槽

    我正在使用 PyQt4 编写我的第一个 Python 应用程序 我有一个 MainWindow 和一个 Dialog 类 它是 MainWindow 类的一部分 self loginDialog LoginDialog 我使用插槽和信号 这
  • 使用 for 循环 Python 为数组赋值

    我正在尝试将字符串的值分配给不同的数组索引 但我收到一个名为 列表分配超出范围 的错误 uuidVal distVal uuidArray distArray for i in range len returnedList for beac
  • 创建一个行为类似于任何变量但具有更改/读取回调的类

    我想创建一个类 其行为类似于 python 变量 但在更改 读取 变量 时调用一些回调函数 换句话说 我希望能够按如下方式使用该类 x myClass change callback read callback 将 x 定义为 myclas
  • python 类的属性不在 __init__ 中

    我想知道为什么下面的代码有效 usr bin env python3 import sys class Car def init self pass if name main c Car c speed 3 c time 5 print c
  • 类型错误:只有长度为 1 的数组可以转换为 Python 标量

    我是 openCV 的初学者 正在尝试分析数独求解器的现有代码 有这一段代码会引发错误 samples np float32 np loadtxt feature vector pixels data responses np float3
  • 熊猫 style.background_gradient 忽略 NaN

    我有以下代码来转储数据帧results到 HTML 表格中 这样的列TIME FRAMES根据seaborn 的颜色图进行着色 import seaborn as sns TIME FRAMES 24h 7d 30d 1y Set CSS
  • 使用 Twisted Python 的 UDP 客户端和服务器

    我想创建一个服务器和客户端 使用 Twisted 从网络发送和接收 UDP 数据包 我已经用 Python 中的套接字编写了此代码 但想利用 Twisted 的回调和线程功能 然而 我需要 Twisted 设计方面的帮助 我想接收多种类型的
  • 计算二维笛卡尔坐标中不规则形状的边界

    我正在寻找一种计算不规则形状边界的解决方案 Lats take a look at Square example 如果我有Minimum x and y and Maximum x and y like MaxX 5 MinX 1 MaxY
  • Mac 上的 Errno 13 权限被拒绝

    我只是测试如何从一个 py 文件调用外部 py 文件 我有 2 个 py 文件 都在同一目录中 这是主要代码 runext py 假设调用 ext py import subprocess subprocess call Users tra
  • pip-tools 的干净设置不会编译非常基本的 pyproject.toml

    使用全新的pip tools设置总是会导致Backend subprocess exited error pyproject toml project dependencies openpyxl gt 3 0 9 lt 4 在仅包含上述 p
  • 安装python启动文件

    我如何安装pythonstartup文件 以便它在命令上运行 例如python myfile py 我尝试将其安装到我的 home myuserUbuntu的目录 但它说我没有足够的权限 此外 不同的地方交替说它应该全部大写或全部小写 前面
  • Python写入dbf数据时出错

    我得到这个错误 DbfError unable to modify fields individually except in with or Process 如何修复它 这是我的code with dbf Table aa dbf as
  • 找到图像特征宽度的正确方法和Python包

    输入是一个在黑色背景上带有彩色 抱歉 垂直线的光谱 给定该带的近似 x 坐标 用 X 标记 我想找到该带的宽度 我对图像处理不熟悉 请引导我前往正确的方法图像处理和Python图像处理package也能起到同样的作用 我认为 PIL Ope
  • 透视包含字符串的 Pandas Dataframe - “没有要聚合的数字类型”错误

    关于此错误有很多问题 但环顾四周后 我仍然无法找到 解决解决方案 我正在尝试用字符串旋转数据框 以使一些行数据变成列 但到目前为止还没有成功 我的 df 的形状
  • 有效积累稀疏 scipy 矩阵的集合

    我有一个 O N NxN 的集合scipy sparse csr matrix 每个稀疏矩阵都有 N 个元素集 我想将所有这些矩阵加在一起以获得一个常规的 NxN numpy 数组 N 约为 1000 矩阵内非零元素的排列使得所得总和肯定不
  • Pymongo 批量插入

    我正在尝试批量插入文档 但批量插入时不会插入超过 84 个文档 给我这个错误 in insert pymongo errors InvalidOperation cannot do an empty bulk insert 是否可以批量插入

随机推荐