Skip to content

Instantly share code, notes, and snippets.

@wyudong
Last active January 23, 2024 14:35
Show Gist options
  • Save wyudong/9c392578c6247e7d1d28 to your computer and use it in GitHub Desktop.
Save wyudong/9c392578c6247e7d1d28 to your computer and use it in GitHub Desktop.
OpenCV: From RGB to CMYK
// 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;
}
@cason-yang
Copy link

How to save a jpeg file with CMYK color sapce?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment