You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyOpenGL显示OpenCV图像:摄像头画面展示Python程序

用OpenCV + PyOpenGL显示摄像头画面的实现方案

嘿,我刚好找到了能满足你需求的基础Python实现方案——结合OpenCV获取摄像头实时画面,再通过PyOpenGL完成渲染显示。下面是完整的可运行代码,还有一些实用的使用小贴士:

import cv2
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy as np
import sys

# 窗口尺寸
width = 1280
height = 720
nRange = 1.0
global capture
capture = None

def cv2array(im):
    h, w, c = im.shape
    a = np.fromstring(im.tostring(), dtype=im.dtype, count=w*h*c)
    a.shape = (h, w, c)
    return a

def init():
    global capture
    # 初始化摄像头,0代表系统默认摄像头
    capture = cv2.VideoCapture(0)
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glEnable(GL_TEXTURE_2D)

def display():
    global capture
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()

    # 读取摄像头的一帧画面
    ret, frame = capture.read()
    if ret:
        # OpenCV默认返回BGR格式,转换成OpenGL需要的RGB格式
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # 调整画面尺寸匹配窗口大小
        frame = cv2.resize(frame, (width, height))
        # 转换为OpenGL可处理的数组格式
        img_data = cv2array(frame)

        # 设置纹理参数,保证画面显示清晰
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        # 将画面数据加载到纹理中
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data)

        # 绘制矩形来承载纹理,实现画面显示
        glBegin(GL_QUADS)
        glTexCoord2f(0.0, 0.0); glVertex2f(-nRange, -nRange)
        glTexCoord2f(1.0, 0.0); glVertex2f(nRange, -nRange)
        glTexCoord2f(1.0, 1.0); glVertex2f(nRange, nRange)
        glTexCoord2f(0.0, 1.0); glVertex2f(-nRange, nRange)
        glEnd()

    glutSwapBuffers()
    glutPostRedisplay()

def reshape(w, h):
    # 窗口大小改变时调整投影,保证画面不会变形
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    if w <= h:
        glOrtho(-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange)
    else:
        glOrtho(-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
    glutInitWindowSize(width, height)
    glutCreateWindow(b"OpenCV + PyOpenGL Camera Feed")
    init()
    glutDisplayFunc(display)
    glutReshapeFunc(reshape)
    glutMainLoop()

if __name__ == "__main__":
    main()

使用小贴士

  • 安装依赖:先确保你已经安装了所需的库,在终端执行以下命令:
    pip install opencv-python pyopengl numpy
    
  • 运行注意事项:
    • 程序会调用系统默认摄像头,记得提前开启摄像头权限
    • 窗口默认尺寸是1280x720,你可以修改代码里的width和height参数来调整大小
    • 关闭窗口可以直接点击右上角的关闭按钮,或者在终端按下Ctrl+C终止程序

内容的提问来源于stack exchange,提问作者PunyCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:04:57