Last active
January 23, 2024 14:35
-
-
Save wyudong/9c392578c6247e7d1d28 to your computer and use it in GitHub Desktop.
OpenCV: From RGB to CMYK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// RGB to CMYK conversion | |
void rgb2cmyk(cv::Mat& img, std::vector<cv::Mat>& cmyk) { | |
// Allocate cmyk to store 4 componets | |
for (int i = 0; i < 4; i++) { | |
cmyk.push_back(cv::Mat(img.size(), CV_8UC1)); | |
} | |
// Get rgb | |
std::vector<cv::Mat> rgb; | |
cv::split(img, rgb); | |
// rgb to cmyk | |
for (int i = 0; i < img.rows; i++) { | |
for (int j = 0; j < img.cols; j++) { | |
float r = (int)rgb[2].at<uchar>(i, j) / 255.; | |
float g = (int)rgb[1].at<uchar>(i, j) / 255.; | |
float b = (int)rgb[0].at<uchar>(i, j) / 255.; | |
float k = std::min(std::min(1- r, 1- g), 1- b); | |
cmyk[0].at<uchar>(i, j) = (1 - r - k) / (1 - k) * 255.; | |
cmyk[1].at<uchar>(i, j) = (1 - g - k) / (1 - k) * 255.; | |
cmyk[2].at<uchar>(i, j) = (1 - b - k) / (1 - k) * 255.; | |
cmyk[3].at<uchar>(i, j) = k * 255.; | |
} | |
} | |
} | |
// Test rgb2cmyk function | |
int main(int argc, char** argv) { | |
// TODO: change filename | |
cv::Mat src = cv::imread("c:\\filename.jpg"); | |
std::vector<cv::Mat> dst; | |
rgb2cmyk(src, dst); | |
// Display results | |
cv::imshow("src", src); | |
cv::imshow("c", dst[0]); | |
cv::imshow("m", dst[1]); | |
cv::imshow("y", dst[2]); | |
cv::imshow("k", dst[3]); | |
cv::waitKey(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to save a jpeg file with CMYK color sapce?