c++將jpg轉換為灰度圖
step1:添加依賴
下載這兩個文件,放在cpp同一目錄下,編譯生成
https://github.com/nothings/stb/blob/master/stb_image_write.h
https://github.com/nothings/stb/blob/master/stb_image.h
step2:C:\Users\wangrusheng\source\repos\CMakeProject1\CMakeProject1\CMakeProject1.cpp
#include <vector>
#include <string>
#include <iostream>// 必須在使用前定義這些宏
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" // 圖像加載庫
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h" // 圖像保存庫void convert_to_grayscale(const std::string& input_path,const std::string& output_path,int quality = 75)
{// 加載原始圖像int width, height, channels;unsigned char* orig_data = stbi_load(input_path.c_str(), &width, &height, &channels, 0);if (!orig_data) {std::cerr << "錯誤:無法加載圖像 " << input_path<< "\n原因: " << stbi_failure_reason() << std::endl;return;}std::cout << "已加載圖像: " << width << "x" << height<< ",通道數: " << channels << std::endl;// 創建灰度數據緩沖區(單通道)std::vector<unsigned char> gray_data(width * height);// 灰度轉換核心算法const float R_WEIGHT = 0.299f;const float G_WEIGHT = 0.587f;const float B_WEIGHT = 0.114f;for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {// 計算當前像素的內存位置const int pixel_index = (y * width + x) * channels;// 獲取RGB分量(自動兼容3/4通道圖像)unsigned char r = orig_data[pixel_index];unsigned char g = orig_data[pixel_index + 1];unsigned char b = orig_data[pixel_index + 2];// 計算灰度值(加權平均法)gray_data[y * width + x] = static_cast<unsigned char>(R_WEIGHT * r +G_WEIGHT * g +B_WEIGHT * b);}}// 保存灰度圖像(JPEG格式)if (!stbi_write_jpg(output_path.c_str(), width, height, 1, gray_data.data(), quality)) {std::cerr << "錯誤:無法保存圖像到 " << output_path << std::endl;}// 釋放原始圖像內存stbi_image_free(orig_data);
}int main() {// 輸入輸出路徑(使用原始字符串避免轉義)const std::string input_file = R"(C:\Users\wangrusheng\Downloads\red.jpg)";const std::string output_file = R"(C:\Users\wangrusheng\Downloads\new_gray.jpg)";// 執行轉換并設置JPEG質量為85%convert_to_grayscale(input_file, output_file, 85);std::cout << "轉換完成,請檢查輸出文件: " << output_file << std::endl;return 0;
}
end