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/zh-tw/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

發表回復

登錄後才能評論