I have a color that I want to convert to a different color space. Is it possible to use cvtColor
on a cv::Vec3f
directly without creating a 1x1 cv::Mat
and populating it with that pixel, using cvtColor
on the cv::Mat
, then getting the only pixel out of the output? I have tried the following, but it doesn't seem to like getting passed a vector.
Any suggestions?
#include <iostream>
#include <opencv2/opencv.hpp>
int main(int, char*[])
{
cv::Vec3f hsv;
hsv[0] = .9;
hsv[1] = .8;
hsv[2] = .7;
std::cout << "HSV: " << hsv << std::endl;
cv::Vec3b bgr;
cvtColor(hsv, bgr, CV_HSV2BGR); // OpenCV Error: Assertion failed (scn == 3 && (dcn == 3 || dcn == 4) && (depth == CV_8U || depth == CV_32F)) in cvtColor
std::cout << "BGR: " << bgr << std::endl;
return EXIT_SUCCESS;
}
I also tried this, but get a different error:
#include <iostream>
#include <opencv2/opencv.hpp>
int main(int, char*[])
{
cv::Mat_<cv::Vec3f> hsv(cv::Vec3f(0.7, 0.7, 0.8));
std::cout << "HSV: " << hsv << std::endl;
cv::Mat_<cv::Vec3b> bgr;
cvtColor(hsv, bgr, CV_HSV2BGR); // OpenCV Error: Assertion failed (!fixedType() || ((Mat*)obj)->type() == mtype) in create
std::cout << "BGR: " << bgr << std::endl;
return EXIT_SUCCESS;
}
cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV.
Since OpenCV represents our image in BGR order rather than RGB, we specify the cv2. COLOR_BGR2HSV flag to indicate that we want to convert from BGR to HSV.
We can use cvtColor() method to convert a BGR image to RGB and vice-versa. Parameter: cv2. COLOR_BGR2RGB – BGR image is converted to RGB.
COLOR_BGR2LAB: This code is used to change the BGR color space to LAB color space.20-Apr-2020.
Your second approach is correct, but you have source and destination of different types in cvtColor
, and that causes the error.
Be sure to have both hsv
and bgr
of the same type, CV_32F
here:
#include <opencv2/opencv.hpp>
#include <iostream>
int main()
{
cv::Mat3f hsv(cv::Vec3f(0.7, 0.7, 0.8));
std::cout << "HSV: " << hsv << std::endl;
cv::Mat3f bgr;
cvtColor(hsv, bgr, CV_HSV2BGR);
std::cout << "BGR: " << bgr << std::endl;
return 0;
}
You can use Mat3f
for brevity. It's just a typedef:
typedef Mat_<Vec3f> Mat3f;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With