Created
April 15, 2022 15:55
-
-
Save Adirockzz95/ae4aaf6f6f65a1eebdf2ea5193770479 to your computer and use it in GitHub Desktop.
Minimal Python example code to display video frames from USB camera using OpenCV, Pygame and OpenGL.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Minimal Python example code to display video frames from USB camera | |
using OpenCV, Pygame and OPENGL. | |
Tested with: | |
Pygame: 1.9.4 | |
OpenCV: 4.5.4 | |
""" | |
import time | |
import cv2 | |
import pygame | |
from OpenGL.GL import * | |
from OpenGL.GLU import * | |
CAM_INDEX = 0 | |
WIDTH, HEIGHT = (640, 480) | |
OPENGL_TEXTURE = glGenTextures(1) | |
PYGAME_FLAGS = pygame.DOUBLEBUF | pygame.OPENGL | |
def bilt_frame(frame): | |
glTexImage2D( | |
GL_TEXTURE_2D, | |
0, | |
GL_RGB, | |
WIDTH, | |
HEIGHT, | |
0, | |
GL_RGB, | |
GL_UNSIGNED_BYTE, | |
frame, | |
) | |
glClear(GL_COLOR_BUFFER_BIT) | |
glLoadIdentity() | |
glBegin(GL_QUADS) | |
glTexCoord(0, 0) | |
glVertex2f(0, 0) | |
glTexCoord(1, 0) | |
glVertex2f(WIDTH, 0) | |
glTexCoord(1, 1) | |
glVertex2f(WIDTH, HEIGHT) | |
glTexCoord(0, 1) | |
glVertex2f(0, HEIGHT) | |
glEnd() | |
pygame.display.flip() | |
glBindTexture(GL_TEXTURE_2D, 0) | |
def init_opengl(): | |
glMatrixMode(GL_PROJECTION) | |
gluOrtho2D(0, WIDTH, 0, HEIGHT) | |
glMatrixMode(GL_MODELVIEW) | |
glLoadIdentity() | |
glDisable(GL_DEPTH_TEST) | |
glClearColor(0.0, 0.0, 0.0, 0.0) | |
glEnable(GL_TEXTURE_2D) | |
glBindTexture(GL_TEXTURE_2D, OPENGL_TEXTURE) | |
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) | |
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) | |
glBindTexture(GL_TEXTURE_2D, 0) | |
def init_pygame(): | |
pygame.display.set_mode((WIDTH, HEIGHT), PYGAME_FLAGS) | |
def quit_pygame(): | |
pygame.display.quit() | |
if __name__ == "__main__": | |
init_pygame() | |
init_opengl() | |
cap = cv2.VideoCapture(CAM_INDEX, cv2.CAP_V4L2) | |
cap.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH) | |
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT) | |
while True: | |
ret, frame = cap.read() | |
if ret: | |
bilt_frame(frame) | |
time.sleep(1 / 25) | |
# hit Ctrl + C to exit the program | |
quit_pygame() | |
cap.release() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment