OpenCV實現更改圖片顏色功能

原圖效果:

更改顏色後效果:

直接上源碼:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>

using namespace cv;
using namespace std;

int main(int argc, char const* argv[])
{
    Mat srcImg = imread("E:/img/kai.png", IMREAD_UNCHANGED); //-1不做任何改變
    Mat srcImg1 = imread("E:/img/kai.png", 0);   //0灰度
    Mat srcImg2 = imread("E:/img/kai.png", 1);  //1是color

    cout << srcImg.channels() << endl;
    cout << srcImg1.channels() << endl;
    cout << srcImg2.channels() << endl;
    
    imshow("-1", srcImg);
    imshow("0", srcImg1);
    imshow("1", srcImg2);

    //顏色有空間 RGB (1) RGBA(-1) 透明度  灰色空間(0)    
    //1、存儲階段的顏色值
    vector<Vec3d> colors;
    unsigned long index = 0;
    for (int i = 0; i < 6; ++i) {
        for (int j = 0; j < 6; ++j) {
            for (int k = 0; k < 6; ++k) {
                colors.push_back(Vec3d());
                colors[index][0] = i / 5.0 * 255;
                colors[index][1] = j / 5.0 * 255;
                colors[index][2] = k / 5.0 * 255;
                index++;
            }
        }
    }
    //2、更對對應的顏色值
    index = 0;
    Mat temp = srcImg.clone();
    while (index < colors.size()) {
        for (int r = 0; r < srcImg.rows; ++r) {
            for (int c = 0; c < srcImg.cols; ++c) {
                //獲取像素點的顏色
                //c4b &pixel = srcImg.at<Vec4b>(r, c);  //4b和4d有區別的,b是uchar, d是double
                Vec4b &pixel_temp = temp.at<Vec4b>(r, c);
                //如果當前點的透明度為0
                if (pixel_temp[3] == 0) {
                    continue;
                } else {
                    for (int i = 0; i < 3; ++i) {
                        pixel_temp[i] = colors[index][i];
                    }
                }
            }     
        }
        //3、保存需要的圖片
        char outImagePath[64] = {};
        sprintf_s(outImagePath, "E:/img/outImagePath/out_img_%.0f_%.0f_%.0f.png", colors[index][0], colors[index][1], colors[index][2]);
        imwrite(outImagePath, temp);
        index++;
    }   
    //waitKey(0);
    return 0;
}

到此這篇關於OpenCV實現更改圖片顏色功能的文章就介紹到這瞭,更多相關OpenCV更改圖片顏色內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: