Opencv打开摄像头详解

一、opencv打开摄像头修改尺寸

1、首先导入相关库文件:

# import necessary packages
import cv2
 
# define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

2、接着打开摄像头:

# open the camera
cap = cv2.VideoCapture(0)
 
# set the width and height of the camera capture
cap.set(3, 640)
cap.set(4, 480)

3、循环读取摄像头画面,完成尺寸的修改:

while(cap.isOpened()):
    # read frames from the camera
    ret, frame = cap.read()
 
    if ret==True:
        # resize the frame
        frame = cv2.resize(frame, (800,600))
 
        # write the resized frame
        out.write(frame)
 
        # display the resized frame
        cv2.imshow('frame',frame)
 
        # break if the 'q' key is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
 
# release the video capture
cap.release()
 
# release the video writer
out.release()
 
# close all the frames
cv2.destroyAllWindows()

二、opencv打开摄像头并识别图形形状

1、首先导入相关库文件:

# import the necessary packages
import imutils
import cv2
 
# define the lower and upper boundaries of the color of the object
colorLower = (24, 100, 100)
colorUpper = (44, 255, 255)

2、接着打开摄像头:

# open the camera
cap = cv2.VideoCapture(0)

3、循环读取摄像头画面,完成图形的识别:

while True:
    # get a frame
    ret, frame = cap.read()
 
    # if we are unable to get a frame, this means we have reached the end of the video
    if not ret:
        break
 
    # resize the frame, blur it, and convert it to the HSV color space
    frame = imutils.resize(frame, width=600)
    blurred = cv2.GaussianBlur(frame, (11, 11), 0)
    hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
 
    # create a mask for the color of the object, then perform the bitwise and operation
    mask = cv2.inRange(hsv, colorLower, colorUpper)
    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)
 
    # find contours in the mask and initialize the current (x, y) center of the object
    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    center = None
 
    # if we have found at least one contour, find the largest one and compute its minimum enclosing circle
    if len(cnts) > 0:
        c = max(cnts, key=cv2.contourArea)
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        M = cv2.moments(c)
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
 
        # if the circle is big enough, draw it and label the current shape
        if radius > 10:
            cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
            cv2.putText(frame, "Circle", (int(x-radius),int(y-radius)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
 
    # display the resulting frame
    cv2.imshow("Frame", frame)
 
    # if the 'q' key is pressed, stop the loop
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
 
# release the camera and close all windows
cap.release()
cv2.destroyAllWindows()

三、opencv打开摄像头代码

使用opencv打开摄像头代码如下:

import cv2
 
cap = cv2.VideoCapture(0)
 
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
 
    # Display the resulting frame
    cv2.imshow('frame',frame)
 
    # if the 'q' key is pressed, stop the loop
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
 
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

四、opencv打开摄像头没画面

如果打开摄像头没有画面,可以检查一下以下两种情况:

1、检查摄像头是否连接好,是否以及设置为默认摄像头;

2、修改代码段中以下这句话:

cap = cv2.VideoCapture(0)

将摄像头的索引修改为1或其他数字,即可打开其他连接上的摄像头。

五、opencv打开摄像头失败

如果打开摄像头失败,可以检查以下几个方面:

1、检查电脑是否有权限读取使用摄像头;

2、检查电脑是否有摄像头设备;

3、修改代码段中以下这句话,在其后添加superuser权限:

cap = cv2.VideoCapture(0)

如下:

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

六、opencv打开摄像头python

在python中使用opencv打开摄像头的代码如下:

import cv2
 
cap = cv2.VideoCapture(0)
 
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
 
    # Display the resulting frame
    cv2.imshow('frame',frame)
 
    # if the 'q' key is pressed, stop the loop
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
 
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

七、opencv打开摄像头并捕捉图像

使用opencv打开摄像头并捕捉图像的代码如下:

import cv2
 
cap = cv2.VideoCapture(0)
 
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
 
    # Display the resulting frame
    cv2.imshow('frame',frame)
 
    # if the space bar is pressed, capture the current frame
    if cv2.waitKey(1) == 32:
        cv2.imwrite('image.jpg', frame)
        print('Image captured')
 
    # if the 'q' key is pressed, stop the loop
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
 
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

八、opencv打开摄像头并保存手势

使用opencv打开摄像头并保存手势的代码如下:

# import the necessary packages
import cv2
import os
 
# define the paths to the training images and the output directory
imagePaths = ["images/1.jpg", "images/2.jpg", "images/3.jpg",
              "images/4.jpg", "images/5.jpg", "images/6.jpg",
              "images/7.jpg", "images/8.jpg", "images/9.jpg"]
outputDir = "gestures"
 
# loop over the training images
for imagePath in imagePaths:
    # load the image, convert it to grayscale, and blur it
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
 
    # threshold the image, erode and dilate it
    thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
    thresh = cv2.erode(thresh, None, iterations=2)
    thresh = cv2.dilate(thresh, None, iterations=2)
 
    # find contours in the thresholded image and sort the contours by area in descending order
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:1]
 
    # initialize the hull list and loop over the contours
    hull = []
    for c in cnts:
        # compute the convex hull of the contour
        hull.append(cv2.convexHull(c))
 
    # draw the contour and convex hull of the hand
    drawing = np.zeros(image.shape[:2], dtype=np.uint8)
    for i in range(len(cnts)):
        cv2.drawContours(drawing, cnts, i, (255, 255, 255), -1)
        cv2.drawContours(drawing, hull, i, (255, 255, 255), -1)
 
    # save the image to disk
    filename = os.path.splitext(os.path.basename(imagePath))[0] + ".png"
    cv2.imwrite(os.path.join(outputDir, filename), drawing)

九、opencv打开摄像头不显示

如果打开摄像头后没有显示,请检查以下几个方面:

1、检查opencv是否安装正确;

2、检查电脑是否有摄像头设备;

3、检查电脑是否设置了防火墙或者杀软是否对opencv进行了限制;

4、修改代码段中以下这句话,添加数据类型转换:

cv2.imshow('frame',frame)

如下:

cv2.imshow('frame', np.uint8(frame))

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/242310.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-12 12:47
下一篇 2024-12-12 12:47

相关推荐

  • 如何在PyCharm中安装OpenCV?

    本文将从以下几个方面详细介绍如何在PyCharm中安装OpenCV。 一、安装Python 在安装OpenCV之前,请确保已经安装了Python。 如果您还没有安装Python,可…

    编程 2025-04-29
  • Python OpenCV 直线检测

    本文将介绍在Python OpenCV中进行直线检测的方法,主要涉及到图像的边缘检测、霍夫变换和绘制直线等操作。 一、边缘检测 由于直线检测是从图像的边缘开始的,因此必须先找到图像…

    编程 2025-04-29
  • Opencv 实现读取 BMP 图片

    Opencv 是一个基于 C/C++ 语言的开源计算机视觉库,可以用于图像处理、特征识别、目标跟踪、机器学习等领域。在图像处理中,读取 BMP 图片是常见操作之一。 一、打开 BM…

    编程 2025-04-27
  • opencv鼠标绘图

    本文将为您详细介绍如何使用opencv在原始图片上进行鼠标绘图。 一、准备工作 在开始绘制之前,您需要先准备好以下的工作: 1、安装opencv库,可以通过pip install …

    编程 2025-04-27
  • Linux sync详解

    一、sync概述 sync是Linux中一个非常重要的命令,它可以将文件系统缓存中的内容,强制写入磁盘中。在执行sync之前,所有的文件系统更新将不会立即写入磁盘,而是先缓存在内存…

    编程 2025-04-25
  • 神经网络代码详解

    神经网络作为一种人工智能技术,被广泛应用于语音识别、图像识别、自然语言处理等领域。而神经网络的模型编写,离不开代码。本文将从多个方面详细阐述神经网络模型编写的代码技术。 一、神经网…

    编程 2025-04-25
  • 详解eclipse设置

    一、安装与基础设置 1、下载eclipse并进行安装。 2、打开eclipse,选择对应的工作空间路径。 File -> Switch Workspace -> [选择…

    编程 2025-04-25
  • Java BigDecimal 精度详解

    一、基础概念 Java BigDecimal 是一个用于高精度计算的类。普通的 double 或 float 类型只能精确表示有限的数字,而对于需要高精度计算的场景,BigDeci…

    编程 2025-04-25
  • Linux修改文件名命令详解

    在Linux系统中,修改文件名是一个很常见的操作。Linux提供了多种方式来修改文件名,这篇文章将介绍Linux修改文件名的详细操作。 一、mv命令 mv命令是Linux下的常用命…

    编程 2025-04-25
  • MPU6050工作原理详解

    一、什么是MPU6050 MPU6050是一种六轴惯性传感器,能够同时测量加速度和角速度。它由三个传感器组成:一个三轴加速度计和一个三轴陀螺仪。这个组合提供了非常精细的姿态解算,其…

    编程 2025-04-25

发表回复

登录后才能评论