I implemented bgr2hsv function by accessing pixels with OpenCV, C++.
I just coded it with bgr2hsv algorithm on the Internet.
And I compared my bgr2hsv()
to cvtColor()
results.
Actually, result images has a little different colors even though the original image was same. I tried to see why different but I couldn't find it. Could you see the source codes and result images? Here's the code.
//self-made bgr2hsv
double b, g, r;
double bb, gg, rr;
double tmax, tmin;
double h = 0, s = 0, v = 0;
double del, delB, delG, delR;
Mat image = imread("lena.jpg", 1);
Mat clone1 = image.clone();
Mat img;
image.convertTo(img, CV_64F);
for (int y = 0; y < img.rows; y++)
{
for (int x = 0; x < img.cols; x++)
{
b = image.at<Vec3b>(y, x)[0];
g = image.at<Vec3b>(y, x)[1];
r = image.at<Vec3b>(y, x)[2];
bb = b / 255;
gg = g / 255;
rr = r / 255;
tmax = _max(bb, gg, rr);
tmin = _min(bb, gg, rr);
v = tmax;
del = tmax - tmin;
if (del == 0) {
h = 0;
s = 0;
}
else {
s = del / tmax;
delB = ((tmax - b) / 6 + del / 2) / del;
delG = ((tmax - g) / 6 + del / 2) / del;
delR = ((tmax - r) / 6 + del / 2) / del;
if (b == tmax) {
h = (2 / 3) + delG - delR;
}
if (g == tmax) {
h = (1 / 3) + delR - delB;
}
if (r == tmax) {
h = delB - delG;
}
if (h < 0) h += 1;
if (h > 1) h -= 1;
}
img.at<Vec3d>(y, x)[0] = h;
img.at<Vec3d>(y, x)[1] = s;
img.at<Vec3d>(y, x)[2] = v;
}
}
//bgr2hsv with cvtColor
cvtColor(image,clone1,CV_BGR2HSV);
imwrite("implemented_hsv.jpg",clone1);
imwrite("bgr2hsv.jpg", img);
//show images
imshow("bgr2hsv", img);
imshow("implemented_hsv",clone1);
waitKey(0);
And results are here. enter image description here
I wouldn't suggest grabbing something from the internet and expecting it to give you the correct result unless you understand what's going on. Instead of using this, why not just use the formula from the OpenCV docs?
For an example of this particular conversion, see my answer here. It uses the exact formula OpenCV mentions in the docs linked above for BGR to HSV conversion. It's in Python and not C++, but Python is fairly easy to read anyways.