【问题标题】:taking images from webcam从网络摄像头拍摄图像
【发布时间】:2020-07-06 09:11:58
【问题描述】:

我有这个脚本可以从网络摄像头捕获图像,但它没有保存任何图像,我不知道为什么。我收到此错误 "回溯(最近一次调用最后一次): 文件“C:/Users/Iram/.PyCharmCE2019.3/config/scratches/scratch_5.py”,第 26 行,在 灰色 = 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] 全局 C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB 终止异步回调"

我的代码是

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

有人可以帮我吗?

【问题讨论】:

  • 为什么except中的break后面有代码?
  • ——AMC。我不知道,我从哪里得到它

标签: python opencv image-processing computer-vision


【解决方案1】:

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

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

包含冒号字符的文件名是非法的。

  • 图像(帧)未写入文件。
  • 读取图像img_ = cv2.imread('saved_img.jpg,%Y-%b-%d %H:%M:%S', cv2.IMREAD_ANYCOLOR) 返回None
  • None 值传递给cv2.cvtColor 会引发OpenCV 异常。

建议修复:

  • 使用有效文件名,例如:file_name = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M- %S.jpg')
  • 读写时使用变量file_name
  • 我还建议在使用frame 之前验证checkTrue

我创建了一个用于测试的示例代码。
该代码生成合成视频文件,并从生成的文件而不是从相机中读取帧。

这里是测试代码:

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

【讨论】:

  • 你会为网络摄像头或任何其他 USB 摄像头编写代码吗?我必须按“s”才能拍照,可以按一次然后拍照直到按q吗?
  • 我没有用于测试的网络摄像头,但错误与网络摄像头无关。正如我所提到的,代码从视频文件中读取帧。执行我贴的代码,按“s”和“q”... 下断点,用调试器一步步跟着代码走。删除第一部分(构建合成视频)。将webcam = cv2.VideoCapture(intput_filename) 替换为webcam = cv2.VideoCapture(0)。将key = cv2.waitKey(100) 改回key = cv2.waitKey(1)。并检查...
猜你喜欢
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 2015-04-18
相关资源
最近更新 更多