opencv等比例缩放图像 c++
时间: 2023-10-13 19:06:55 浏览: 79
可以使用OpenCV库来实现等比例缩放图像。下面是使用C语言的示例代码:
```c
#include <opencv2/opencv.hpp>
int main() {
// 读取原始图像
cv::Mat srcImage = cv::imread("input.jpg");
// 设置缩放比例
double scale = 0.5;
// 计算缩放后的图像尺寸
cv::Size dstSize(srcImage.cols * scale, srcImage.rows * scale);
// 进行缩放操作
cv::Mat dstImage;
cv::resize(srcImage, dstImage, dstSize);
// 显示原始图像和缩放后的图像
cv::imshow("Original Image", srcImage);
cv::imshow("Scaled Image", dstImage);
cv::waitKey(0);
return 0;
}
```
在上述代码中,我们首先使用`imread`函数读取原始图像。然后,通过设置`scale`变量来定义缩放比例。根据缩放比例,我们计算出缩放后的图像尺寸。最后,使用`resize`函数进行图像缩放操作,并显示原始图像和缩放后的图像。
请注意,你需要安装OpenCV库并将其与你的项目链接。在编译时,可能需要指定相应的头文件和库文件路径。
相关问题
opencv c++如何缩放图片为指定大小
可以使用OpenCV中的resize函数来缩放图像。以下是使用C++和OpenCV将图像缩放为指定大小的示例代码:
```cpp
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取图像
Mat img = imread("test.jpg");
// 缩放图像为指定大小
Size size(640, 480);
Mat resized_img;
resize(img, resized_img, size);
// 显示原始图像和缩放后的图像
imshow("Original Image", img);
imshow("Resized Image", resized_img);
waitKey(0);
return 0;
}
```
在上面的代码中,我们首先使用imread函数读取图像,然后使用resize函数将图像缩放为指定大小。最后使用imshow函数显示原始图像和缩放后的图像。
opencv c++ 图片等比例拉伸
在 OpenCV 中,可以使用 resize() 函数来对图像进行缩放操作,从而实现图片等比例拉伸。具体来说,可以按照以下步骤进行操作:
1. 读取原始图像,获取其宽度和高度。
2. 计算目标图像的宽度和高度,假设要将原始图像等比例缩放为宽度为 targetWidth,高度为 targetHeight 的目标图像,可以按照以下公式计算:
- 如果原始图像宽度小于等于目标宽度,并且高度小于等于目标高度,则不需要进行缩放,直接使用原始图像即可。
- 如果原始图像宽度小于等于目标宽度,但高度大于目标高度,则按照原始图像高度和目标高度的比例缩放宽度,然后将高度设置为目标高度。
- 如果原始图像宽度大于目标宽度,但高度小于等于目标高度,则按照原始图像宽度和目标宽度的比例缩放高度,然后将宽度设置为目标宽度。
- 如果原始图像宽度大于目标宽度,并且高度大于目标高度,则分别按照原始图像宽度和目标宽度的比例缩放高度,以及按照原始图像高度和目标高度的比例缩放宽度,然后选择缩放比例较小的那个,保证图像等比例缩放。
3. 使用 resize() 函数将原始图像缩放为目标图像大小。具体来说,可以按照以下代码进行操作:
```c++
cv::Mat srcImage = cv::imread("input.jpg");
cv::Mat dstImage;
int targetWidth = 800;
int targetHeight = 600;
int srcWidth = srcImage.cols;
int srcHeight = srcImage.rows;
if (srcWidth <= targetWidth && srcHeight <= targetHeight) {
// 不需要缩放
dstImage = srcImage.clone();
} else if (srcWidth <= targetWidth && srcHeight > targetHeight) {
// 按照高度缩放
int scale = targetHeight / srcHeight;
int dstWidth = srcWidth * scale;
cv::resize(srcImage, dstImage, cv::Size(dstWidth, targetHeight));
} else if (srcWidth > targetWidth && srcHeight <= targetHeight) {
// 按照宽度缩放
int scale = targetWidth / srcWidth;
int dstHeight = srcHeight * scale;
cv::resize(srcImage, dstImage, cv::Size(targetWidth, dstHeight));
} else {
// 按照较小比例缩放
float scaleWidth = (float)targetWidth / srcWidth;
float scaleHeight = (float)targetHeight / srcHeight;
float scale = std::min(scaleWidth, scaleHeight);
int dstWidth = srcWidth * scale;
int dstHeight = srcHeight * scale;
cv::resize(srcImage, dstImage, cv::Size(dstWidth, dstHeight));
}
```
在这里,使用了 cv::Size() 函数来创建目标图像的大小,然后将原始图像传入 resize() 函数中,即可得到缩放后的目标图像。