您的位置:

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))