当前位置: 首页> 文旅> 旅游 > opencv c++ python获取摄像头默认分辨率及设置缩放倍数

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

时间:2025/7/14 1:17:51来源:https://blog.csdn.net/ivanwfy/article/details/140110171 浏览次数:1次

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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: