本文介绍了从网络摄像头拍摄图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本可以从网络摄像头捕获图像,但是它没有保存任何图像,我不知道为什么.我收到此错误"回溯(最近通话一次):在第26行中输入文件"C:/Users/Iram/.PyCharmCE2019.3/config/scratches/scratch_5.py"灰色= cv2.cvtColor(img_,cv2.COLOR_BGR2GRAY)cv2.error:OpenCV(4.2.0)C:\ projects \ opencv-python \ opencv \ modules \ imgproc \ src \ color.cpp:182:error:(-215:Assertion failed)!_src.empty()在函数中'cv :: cvtColor'[WARN:0]全局C:\ projects \ opencv-python \ opencv \ modules \ videoio \ src \ cap_msmf.cpp(674)SourceReaderCB :: ~~ SourceReaderCB终止异步回调"

I have this script to capture images from webcam, but it is not saving any image, I donot know why. I am getting this error"Traceback (most recent call last): File "C:/Users/Iram/.PyCharmCE2019.3/config/scratches/scratch_5.py", line 26, in gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback"

我的代码是

import cv2
import datetime
i = 1
key = cv2.waitKey(1)
webcam = cv2.VideoCapture(0)
while True:
    try:
        check, frame = webcam.read()
        print(check)  # prints true as long as the webcam is running
        print(frame)  # prints matrix values of each framecd
        cv2.imshow("Capturing", frame)
        key = cv2.waitKey(1)
        if key == ord('s'):
            cv2.imwrite(filename='saved_img.jpg,%Y-%b-%d %H:%M:%S', img=frame)
            #print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
            i += 1
            print('%i')

            # webcam.release()
            img_new = cv2.imread('saved_img.jpg,%Y-%b-%d %H:%M:%S', cv2.IMREAD_GRAYSCALE)
            # cv2.imshow("Captured Image", img_new)
            # cv2.waitKey(1925)
            print("Processing image...")
            img_ = cv2.imread('saved_img.jpg,%Y-%b-%d %H:%M:%S', cv2.IMREAD_ANYCOLOR)
            print("Converting RGB image to grayscale...")
            gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)
            print("Converted RGB image to grayscale...")
            print("Resizing image to 28x28 scale...")
            img_ = cv2.resize(gray, (28, 28))
            print("Resized...")
            img_resized = cv2.imwrite(filename='saved_img-final.jpg', img=img_)
            print("Image saved!")

        elif key == ord('q'):
            print("Turning off camera.")
            webcam.release()
            print("Camera off.")
            print("Program ended.")
            cv2.destroyAllWindows()
            break

    except(KeyboardInterrupt):
        print("Turning off camera.")
        webcam.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        camera.release()

        break
        camera.release()
        cv2.destroyAllWindows()

有人可以帮我吗?

推荐答案

错误的根源是您使用的文件名带有冒号 :字符.

The source of the error is that you are using file name with colon : character.

cv2.imwrite(filename='saved_img.jpg,%Y-%b-%d %H:%M:%S', img=frame)

包含冒号的文件名是非法的.

File name containing a colon character is illegal.

  • 图像(框架)未写入文件.
  • 读取图像 img_ = cv2.imread('saved_img.jpg,%Y-%b-%d%H:%M:%S',cv2.IMREAD_ANYCOLOR)返回没有.
  • None 值传递给 cv2.cvtColor 会引发OpenCV异常.
  • The image (frame) is not written to the file.
  • Reading the image img_ = cv2.imread('saved_img.jpg,%Y-%b-%d %H:%M:%S', cv2.IMREAD_ANYCOLOR) returns None.
  • Passing None value to cv2.cvtColor raise an OpenCV exception.

建议的解决方法:

  • 使用有效文件名,例如: file_name = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S.jpg')
  • 读写时使用变量 file_name .
  • 我还建议在使用 frame 之前,先验证 check 是否为 True .
  • Use valid file name like: file_name = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S.jpg')
  • Use the variable file_name when reading and writing.
  • I am also suggesting to verify that check is True before using frame.

我创建了一个示例代码进行测试.
该代码生成合成视频文件,并从生成的文件而不是从摄像机读取帧.

I created a sample code for testing.
The code generates synthetic video file, and read frames from the generated file instead of from camera.

这是测试代码:

import numpy as np
import cv2
import datetime

intput_filename = 'input_vid.avi'

# Generate synthetic video files to be used as input:
###############################################################################
width, height, n_frames = 640, 480, 100  # 100 frames, resolution 640x480

# Use motion JPEG codec (for testing)
synthetic_out = cv2.VideoWriter(intput_filename, cv2.VideoWriter_fourcc(*'MJPG'), 25, (width, height))

for i in range(n_frames):
    img = np.full((height, width, 3), 60, np.uint8)
    cv2.putText(img, str(i+1), (width//2-100*len(str(i+1)), height//2+100), cv2.FONT_HERSHEY_DUPLEX, 10, (30, 255, 30), 20)  # Green number
    synthetic_out.write(img)

synthetic_out.release()
###############################################################################


i = 1
key = cv2.waitKey(1)

# Read video from file instead of from camera (for testing)
webcam = cv2.VideoCapture(intput_filename)

while True:
    try:
        check, frame = webcam.read()
        print(check)  # prints true as long as the webcam is running

        if check:
            print(frame)  # prints matrix values of each frame
            cv2.imshow("Capturing", frame)

            if key == ord('s'):
                file_name = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S.jpg')

                cv2.imwrite(file_name, img=frame)
                #print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
                i += 1
                print(str(i))

                # webcam.release()
                img_new = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)
                # cv2.imshow("Captured Image", img_new)
                # cv2.waitKey(1925)
                print("Processing image...")
                img_ = cv2.imread(file_name, cv2.IMREAD_ANYCOLOR)
                print("Converting RGB image to grayscale...")
                gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)
                print("Converted RGB image to grayscale...")
                print("Resizing image to 28x28 scale...")
                img_ = cv2.resize(gray, (28, 28))
                print("Resized...")
                img_resized = cv2.imwrite(filename='saved_img-final.jpg', img=img_)
                print("Image saved!")

        #key = cv2.waitKey(1)
        key = cv2.waitKey(100)  # Wait 100 msec (just for testing).

        if key == ord('q'):
            print("Turning off camera.")
            print("Camera off.")
            print("Program ended.")
            break

    except(KeyboardInterrupt):
        print("Turning off camera.")
        print("Camera off.")
        print("Program ended.")
        break

webcam.release()
cv2.destroyAllWindows()

这篇关于从网络摄像头拍摄图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 22:23