OpenCV升级了网络摄像头的提要,而不是使用全分辨率

2024-04-23 06:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个1080p的网络摄像头(罗技v-u0032),我正在创建一个程序,保存它的饲料仍然每X秒,但图像有黑色的酒吧和决议似乎低于仍然采取与Windows内置的相机应用程序,两者的输出文件有1920x1080像素,但在实际分辨率的差异是非常明显的

我一直在寻找改变分辨率的方法,但是OpenCV似乎总是升级到新的分辨率

import cv2
import numpy as np
import datetime
import time
import os

cv2.namedWindow("Unregistered Hypercam")
vc = cv2.VideoCapture(0)

vc.set(3, 1920) # Set the horizontal resolution
vc.set(4, 1080) # Set the vertical resolution
vc.set(5, 10)   # Set the framerate

if vc.isOpened():
    rval, frame = vc.read()
else:
    rval = False

lastSave = time.time()

def mfold(name):
    try:  
         os.mkdir(name)
    except OSError:  
         x = 0
    else:  
        print ("Successfully created the directory %s " % fold)

while rval:
    cv2.imshow("Unregistered Hypercam", frame)
    rval, frame = vc.read()
    now = datetime.datetime.now()

    if time.time() > lastSave + 10:
        lastSave = time.time()
        fold = '\\snapshots\\' # This will create folder C:\snapshots
        mfold(fold)
        cv2.imwrite(fold + str(now.year) + '.' + str(now.month) + '.' + str(now.day) + '  ' + str(now.hour) + 'h_' + str(now.minute) + 'm_' + str(now.second) + 's.png', frame)

    key = cv2.waitKey(20)
    if key == 27:
        break

cv2.destroyWindow("Unregistered Hypercam")

图像模糊且不清晰,带有黑色条,与Windows摄像头应用程序拍摄的图像完全不同


Tags: the图像importdatetimetime分辨率foldcv2
1条回答
网友
1楼 · 发布于 2024-04-23 06:08:50

下面是一个示例小部件,用于将网络摄像头/流保存到视频文件或屏幕截图图像中。它保持流的原始分辨率。我用了我的一个IP摄像头流而不是一个网络摄像头,但它应该与一个网络摄像头工作相同。目前,它打开一个流,并将其保存为视频,但你可以修改它采取定期截图。此外,要修改分辨率,您可以手动调整帧的大小,同时使用此函数保持纵横比(该函数当前未在小部件中使用)。你知道吗

在保持纵横比的同时调整帧的分辨率

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the 0idth and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

你可以这样用它来调整宽度或高度

rval, frame = vc.read()

resize_width = maintain_aspect_ratio_resize(frame, width=500)
resize_height = maintain_aspect_ratio_resize(frame, height=500)

流式传输和保存视频小部件

from threading import Thread
import cv2

class VideoWriterObject(object):
    def __init__(self, src=0):
        # Create a VideoCapture object
        self.capture = cv2.VideoCapture(src)

        # Default resolutions of the frame are obtained (system dependent)
        self.frame_width = int(self.capture.get(3))
        self.frame_height = int(self.capture.get(4))

        # Set up codec and output video settings
        self.codec = cv2.VideoWriter_fourcc('M','J','P','G')
        self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height))

        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()

    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):
        # Display frames in main program
        if self.status:
            cv2.imshow('frame', self.frame)

        # Press Q on keyboard to stop recording
        key = cv2.waitKey(1)
        if key == ord('q'):
            self.capture.release()
            self.output_video.release()
            cv2.destroyAllWindows()
            exit(1)

    def save_frame(self):
        # Save obtained frame into video output file
        self.output_video.write(self.frame)

if __name__ == '__main__':
    video_stream_widget = VideoWriterObject(0)
    while True:
        try:
            video_stream_widget.show_frame()
            video_stream_widget.save_frame()
        except AttributeError:
            pass

相关问题 更多 >