opencv c++ python获取摄像头默认分辨率及设置缩放倍数

发布于:2024-07-02 ⋅ 阅读:(17) ⋅ 点赞:(0)

c++代码

#include <opencv2/opencv.hpp>
#include <iostream>

int main() {
    // 创建一个VideoCapture对象
    cv::VideoCapture cap(0); // 参数0表示打开默认摄像头

    // 检查摄像头是否成功打开
    if (!cap.isOpened()) {
        std::cerr << "Error: Could not open camera" << std::endl;
        return -1;
    }

    // 获取摄像头的默认分辨率
    int frame_width = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
    int frame_height = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));

    std::cout << "Default resolution: " << frame_width << "x" << frame_height << std::endl;

    // 设置缩放倍数
    double scale = 0.5; // 可以调整这个值来放大或缩小窗口

    // 计算新的窗口大小
    int window_width = static_cast<int>(frame_width * scale);
    int window_height = static_cast<int>(frame_height * scale);

    // 创建一个窗口用于显示视频
    cv::namedWindow("Camera", cv::WINDOW_NORMAL); // 使用cv::WINDOW_NORMAL以便可以调整窗口大小
    cv::resizeWindow("Camera", window_width, window_height); // 设置窗口大小

    while (true) {
        cv::Mat frame;
        
        // 读取当前帧
        cap >> frame;

        // 检查帧是否为空
        if (frame.empty()) {
            std::cerr << "Error: Could not read frame" << std::endl;
            break;
        }

        // 调整帧的大小
        cv::Mat resized_frame;
        cv::resize(frame, resized_frame, cv::Size(window_width, window_height)); // 调整帧大小

        // 显示调整后的帧
        cv::imshow("Camera", resized_frame);

        // 按下ESC键退出
        if (cv::waitKey(30) == 27) {
            break;
        }
    }

    // 释放摄像头
    cap.release();

    // 销毁窗口
    cv::destroyAllWindows();

    return 0;
}

python代码

以下是使用Python和OpenCV实现相同功能的代码,它将从摄像头读取视频流、调整窗口大小并显示视频:

import cv2

# 创建一个VideoCapture对象
cap = cv2.VideoCapture(0)  # 参数0表示打开默认摄像头

# 检查摄像头是否成功打开
if not cap.isOpened():
    print("Error: Could not open camera")
    exit()

# 获取摄像头的默认分辨率
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

print(f"Default resolution: {frame_width}x{frame_height}")

# 设置缩放倍数
scale = 0.5  # 可以调整这个值来放大或缩小窗口

# 计算新的窗口大小
window_width = int(frame_width * scale)
window_height = int(frame_height * scale)

# 创建一个窗口用于显示视频
cv2.namedWindow("Camera", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Camera", window_width, window_height)

while True:
    # 读取当前帧
    ret, frame = cap.read()

    # 检查帧是否为空
    if not ret:
        print("Error: Could not read frame")
        break

    # 调整帧的大小
    resized_frame = cv2.resize(frame, (window_width, window_height))

    # 显示调整后的帧
    cv2.imshow("Camera", resized_frame)

    # 按下ESC键退出
    if cv2.waitKey(30) == 27:
        break

# 释放摄像头
cap.release()

# 销毁窗口
cv2.destroyAllWindows()