问题二:用C++输出第一张图片

将书上对应的代码抄写了一遍。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int nx = 200;
    int ny = 100;

    ofstream outfile( "mytest.txt", ios_base::out);
    outfile << "P3\n" << nx << " " << ny << "\n255\n";

    std::cout << "P3\n" << nx << " " << ny << "\n255\n";
    for (int j = ny-1; j >= 0; j--)
    {
        for (
C++ 中读取图片的宽和高,通常需要依赖第三方库,因为标准库本身并不支持图像处理。常见的图像处理库包括 [OpenCV](https://opencv.org/)、[CImg](https://cimg.eu/)、[stb_image](https://github.com/nothings/stb) 等。 下面我将使用 OpenCV 来读取一张图片的宽度和高度,并输出它们。 ### 使用 OpenCV 读取图片宽高 ```cpp #include <iostream> #include <opencv2/opencv.hpp> // OpenCV 头文件 int main() { // 读取图片路径,请替换为你自己的图片路径 std::string image_path = "test.jpg"; // 使用 OpenCV 读取图片 cv::Mat image = cv::imread(image_path, cv::IMREAD_COLOR); // 检查图片是否成功加载 if (image.empty()) { std::cerr << "无法加载图片: " << image_path << std::endl; return -1; } // 获取图片的宽度和高度 int width = image.cols; // 宽度 int height = image.rows; // 高度 // 输出图片的宽度和高度 std::cout << "图片宽度: " << width << std::endl; std::cout << "图片高度: " << height << std::endl; return 0; } ``` ### 代码解释: 1. `cv::Mat image = cv::imread(image_path, cv::IMREAD_COLOR);` - 使用 `imread` 函数读取图片,返回一个 `cv::Mat` 类型的对象。 - `cv::IMREAD_COLOR` 表示以彩色图像的方式读取(忽略透明通道)。 2. `image.cols` 和 `image.rows`: - `cols` 表示图像的列数,即宽度(width)。 - `rows` 表示图像的行数,即高度(height)。 3. 图像路径需要替换为你本地存在的图片路径,支持的格式包括 `.jpg`, `.png`, `.bmp` 等。 ### 编译方法(使用 g++ 和 pkg-config): 确保你已经安装了 OpenCV,并使用如下命令编译: ```bash g++ read_image_size.cpp -o read_image_size `pkg-config --cflags --libs opencv4` ``` ### 运行程序: ```bash ./read_image_size ``` ---
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值