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更改图片颜色内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

若文章对您有帮助,帮忙点个赞!

0
0
发布时间 2022-05-14 15:03:32
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)