Fast branchless RGB to HSV conversion in GLSL

Some time ago I devised an original algorithm to convert from RGB to HSV using very few CPU instructions and I wrote a small article about it.

When looking for a GLSL or HLSL conversion routine, I have found implementations of my own algorithm. However they were almost all straightforward, failing to take full advantage of the GPU’s advanced swizzling features.

So here it is, the best version I could come up with:

vec3 rgb2hsv(vec3 c)
{
    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));

    float d = q.x - min(q.w, q.y);
    float e = 1.0e-10;
    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}

Update: Emil Persson suggests using the ternary operator explicitly to force compilers into using a fast conditional move instruction:

    vec4 p = c.g < c.b ? vec4(c.bg, K.wz) : vec4(c.gb, K.xy);
    vec4 q = c.r < p.x ? vec4(p.xyw, c.r) : vec4(c.r, p.yzx);

And because a lot of people get it wrong, too, here is the reverse operation in GLSL. It is the algorithm almost everyone uses (or should use):

vec3 hsv2rgb(vec3 c)
{
    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

Porting to HLSL is straightforward: replace vec3 and vec4 with float3 and float4, mix with lerp, fract with frac, and clamp(…, 0.0, 1.0) with saturate(…).

  • Posted: 2013-07-27 15:23 (Updated: 2013-07-28 11:54)
  • Author: sam
  • Categories: glsl optim

Comments

1. jhincapie@gmail.com -- 2014-02-23 21:54

Hello Sam, thanks for the code. Do you have a similar GLSL snippet for RGB2HSL?

2. ian@chilliant.com -- 2014-04-23 23:23

Thanks for sharing the optimization, Sam. It really is very elegant. Though am I right in thinking there's a faster HSV-to-RGB? http://blog.chilliant.com/2014/04/rgbhsv-in-hlsl-5.html

@jhincapie: I've put HLSL snippets, including the RGB-to-HSL conversion, on http://www.chilliant.com/rgb2hsv.html

3. anonymous -- 2014-04-24 04:13

Thanks again for this. Just wanted to point out that obviously length(hsv2rgb(foo)) varies, so if you are accumulating the output (as I often do in some kind of glow effect), you'll notice that cyan, magenta, yellow, especially pastels, and of course whites are overexposed much sooner than mostly-saturated red, green, or blue. I work around this by normalizing the last mix before applying the gain, like so:

return c.z * normalize(mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y));
4. anonymous -- 2014-09-05 01:03

I am looking to manipulate only the v channel of an image and do not need to touch the h and s channels. So I only need the h and s to get back to RGB after modifying the v. I am wondering if there is a way in this case to save computation by not fully computing h and s and instead only compute enough information which can be combined with the updated v value to get back to RGB?

5. anonymous -- 2014-10-28 18:33

@anonymous -- 2014-09-05 01:03

If you need only V, why not just compute "max(r, max(g, b))"?

I doubt there is anything faster than that if you need nothing else.

6. anonymous -- 2014-11-13 23:14

@anonymous -- 2014-09-05 01:03

also if you don't need to know what V is before you change it, you can just multiply your RGB vector by a float to linearly scale it, then V is the only hsv-space component that changes (unless any RGB component goes out of range and gets clamped at 0 or 1, that *will* change H and/or S). Look at the last line of rgb2hsv(): c.z is the incoming V component, applied linearly to the intermediate RGB result from mix(). simplest part, really

7. anonymous -- 2014-12-02 21:05

P.S. I meant last line of hsv2rgb() not rgb2hsv(), sorry :( Also Anon.#5's answer is right, max(r, max(g, b)) is essentially the V extraction in sam's linked article about fast rgb to hsv. If you intend to increase V by multiplying then the maximum that will preserve H and S is 1/max(r, max(g,b)).

8. anonymous -- 2016-04-18 00:50

Thanks!

I need RGB 2 HSV but I only need the "VALUE". Is there way to do this with less code so to save a bit on computations?

9. CherishKevin -- 2017-10-12 11:11

Just to tell you that my hard drive chose to "resign" throughout the night, well, it's dead at this point. Right now I'm on a live session of Crunchbang that I figured out how to make function. What's more, I are very brave as well, so I won't generally have the capacity to make additionally coding on this, in any event for the forthcoming week. Yet, we have time. For more information please come to our website http://www.instantassignment.co.uk/

10. anonymous -- 2017-10-14 08:54

Free online bejeweled 3 has the awesome collection for every one worth of free http://bejeweled3.c . Guys you can connect with it with out and down loading and registration.

11. wondergirl -- 2017-10-17 11:55

Is there a way to convert HSV values into HTML? I have a color that is H=50%, S=97%, V=93%. Is there a way to do this? Thanks in advance for your help! http://www.assignmentdoer.co.uk

12. maria denial -- 2017-10-23 09:54

inside the colour picker you may select H/S/B values (click the radio button to map one of the values to the slider; it defaults to Hue as that is typically the most useful). in the color Panel you may pick out HSB sliders with the aid of going to the Panel Menu and choosing "HSB Sliders" – but this might be now not to be had in CS2 as they have made some changes to the coloration Panel because then. http://www.assignmentninja.co.uk/

13. anonymous -- 2017-10-30 07:40

Can you provide me a similar GLSL snippet for RGB2HSL? Thanks much! http://www.kicksvovo.com/

14. anonymous -- 2017-11-02 08:41

got hacked _ an you provide me a similar GLSL snippet for RGB2HSL? Thanks much!

15. anonymous -- 2017-11-02 08:41

Lol

16. anonymous -- 2017-11-02 08:42

RIP GS

17. Gracie Flora -- 2017-11-04 12:43

The above change was at the "cost" of a major information design change known as exhibit of structures to structure of clusters. When working in parallel on comparable information, it is frequently a smart thought, and the GPU was no special case here. http://www.courseworkcamp.co.uk/

18. anonymous -- 2017-11-08 10:40

Get super mario run hack and cheats from http://supermariohacks.net to unlock all the levels of super mario games completely free of cost.

19. free psn codes list -- 2017-11-25 08:25

Free PSN codes generator gives more details. <a href="https://freepsncodesnosurvey.club/">free psn codes list</a>

21. Visual Basic Project Help -- 2017-12-14 11:55

Really i appreciate the effort you made to share the knowledge. This is really a great stuff for sharing. Keep it up . Thanks for sharing.

http://vbhelponline.com/

22. anonymous -- 2017-12-20 06:28

Hi buddy, your blog' s design is simple and clean and i like it. Your blog posts about Online writing Help are superb. Please keep them coming. Greets! https://bellevueHeating.xyz

23. anonymous -- 2017-12-27 23:37

Great algorithm,thanks for sharing. It is really useful for me. https://dietarious.com

24. anonymous -- 2017-12-28 11:34

Hi, guys I like your Blog, your post has good information I really interesting to read your post

http://www.certvalue.com/iso-27001-certification-in-delhi/

25. <a href="http://jobs.3beasts.com/">paperpk</a> -- 2017-12-30 19:44

Wow thanks a lot for this kind information, i would be very happy to share some information. Can you please tell me how to write an article to catch traffic.

26. anonymous -- 2018-01-04 11:03

Hi,Hello very interesting ,good article nice infromation i really interesting to read thanks for sharing

<a href="http://www.certvalue.com/iso-9001-certification-in-turkey/">ISO 9001 Audit in Turkey</a>

<a href="http://www.certvalue.com/iso-22000-certification-in-iran/">ISO 22000 Cost in Iran</a>

27. Oliver -- 2018-01-04 15:28

Wow, thanks for sharing the code. I was trying to solve the conversion problem.

Oliver - http://www.ebuske.com/formula-negocio-online/

28. anonymous -- 2018-01-05 11:05

This is really a great stuff for sharing. Keep it up .Thanks for sharing. https://statskey.com/

29. hvac Tacoma WA -- 2018-01-06 12:32

Dissertation Guidance Provides quality Online Dissertation Help for students. <a href="https://tacomaheating.xyz/">hvac Tacoma WA</a>

30. dissertation help uk -- 2018-01-08 08:31

Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have https://www.dissertationwriting.uk/

31. Antoniokim -- 2018-01-08 14:19

I really like it your story, I'm studying you're published so I'm very stimulated due to the fact I love hunting and I am visited distinct different searching locations with my buddies. Proper work and preserve it up thanks. http://www.topcelebsjackets.com/product/jason-momoa-justice-league-aquaman-coat

32. anonymous -- 2018-01-12 11:14

Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have . . .

http://hdwonn.co/ http://buygenericpropecia24.com/

33. Norman -- 2018-01-15 07:39

I am happy to be on your website, you have mentioned about convert from RGB to HSV using very few CPU instructions which i found very interesting to read. I have been searching for such article for some days, now i feel lucky to find on your website. Purchase furniture casters from http://furniturecasters.uk/

34. anonymous -- 2018-01-15 12:34

Good way of telling, good post to take facts regarding my presentation subject matter, which i am going to deliver in my college https://TheCaseSolutions.net

35. yahoo mail login -- 2018-01-16 13:00

Yahoo is one of the oldest web service providers in the world. Yahoo was founded in 1994 byJerry Yan and David Filo and was incorporated on Marc 2, 1995. <a href="https://www.ymaillogin.org/">yahoo mail login</a>

36. Finance Assignments -- 2018-01-17 08:24

Thanks a lot for the post. It has helped me get some nice ideas. I hope I will see some really good result soon. https://www.finance-assignments.com/

37. R Programming Homework Help -- 2018-01-17 13:17

Those who come to read your article will find lots of helpful and informative tipshttps://rprogramminghelp.xyz/

38. anonymous -- 2018-01-18 05:34

hello.. really very informative and useful post.. thanks or sharing this http://www.certvalue.com/iso-22000-certification-dubai/

39. Eleston -- 2018-01-18 10:27

I am very happy to visit in the post. In the post is very interesting and informative for me. I see in the post some different kinds of the bar coding. Thanks for sharing in the post. keep it up. http://www.londonbricks-uk.co.uk/

40. Help With C# Programming Homework -- 2018-01-19 08:33

I Personally Like Your Post; http://csharpaid.com/ You Have Shared Good Insights And Experiences. Keep It Up.

41. gmod -- 2018-01-19 23:29
42. grungy -- 2018-01-21 01:43

This is awesome information from lolengine I applaud your post and hope you deliver more, you should see https://psnzone.com

43. Kelly Lombard -- 2018-01-21 01:52

wow I can't believe I can get this kind of information here https://imvucredits.net , excellent

44. VishnuSux -- 2018-01-21 06:03

Hey man I heard you can get free steam gift codes at https://steamrepo.com

45. Accounting Dissertation Writing Service -- 2018-01-22 07:52

By Visiting This Site I Found Cool Stuff Here Keep It Up. http://www.accountingdissertations.com/

46. Project Help -- 2018-01-25 08:28

Well thanks for posting such an outstanding idea. I like this blog & I like the topic and thinking of making it right. <a href="https://databaseprojecthelp.xyz/">Project Help</a>

47. help with programming homework -- 2018-01-25 09:39

http://www.domyprogramminghomework.net/ I Personally Like Your Post, You Have Shared Good Article. It Will Help Me In Great Deal.

48. Help With Psychology Homework -- 2018-01-30 12:41

Good way of telling, good post to take facts regarding my presentation subject matter, which i am going to deliver in my college https://www.psychologyassignments.com/

49. certvalue143 -- 2018-02-05 11:56

hello.. thanks for sharing such a nice information i really appreciate your work in this and looking for more such good posts in the future thank you http://www.certvalue.com/haccp-certification-in-bahrain/

51. anonymous -- 2018-02-06 20:14

Beautiful content, it brings enough I needed, thank you for posting https://www.montarproprionegocio.com.br/curso-de-manutencao-de-celular/

52. anonymous -- 2018-02-07 07:11

This Nutralyfe Re-gain is known among the users for providing a quick impact on re-growing hairs by nourishing scalp and hairs. Apart from it, this supplement is also become popular for reducing the hair thinning & sparseness by preventing hair damage. http://nutralyferegainreviews.com/

53. Garcinia -- 2018-02-07 07:12

Garcinia Cambogia Herbs is well known as HCA that is clinically proven for its effectiveness in weight management. This anti-obesity drug is also used for blood pressure control and maintaining the cholesterol level. It is pure, 100% natural and has no side effects at all. http://nutralyfegarciniareviews.com/

54. kohinoor XL -- 2018-02-07 07:12

People throughout the world appreciate Kohinoor XL as it lengthens the muscle of male organ, provides extended pleasure at night, and also act as a natural aphrodisiac. Due to the herbal ingredients, and no side effect result, it is recommended by the healthcare experts. It is also widely used by the men for strength and vitality enhancement. http://kohinoorxlreviews.com/

55. anonymous -- 2018-02-09 10:54

Thanks a lot for the post. It has helped me get some nice ideas. I hope I will see some really good result soon. thank you

http://www.certvalue.com/iso-22000-certification-kuwait/

57. anonymous -- 2018-02-10 07:33
58. Help With Psychology Projects -- 2018-02-13 11:30

https://www.psychologyassignments.com/ This is great information for students. This article is very helpful i really like this blog thanks. I also have some information relevant for online dissertation help.

59. Sam -- 2018-02-16 12:46

http://www.nrouterlogin.net/ this is good info about router configuration check it out

60. Sam -- 2018-02-20 10:57

good know about routerlogin http://rrouterlogin.net.in/.

61. nutripath Garcinia -- 2018-02-23 07:52

Garcinia Cambogia Herbs is well known as HCA that is clinically proven for its effectiveness in weight management. This anti-obesity drug is also used for blood pressure control and maintaining the cholesterol level. It is pure, 100% natural and has no side effects at all. http://www.nutripathgarcinia.com/

62. ทางเข้า gclub -- 2018-02-24 19:00

Ready? Click a <a href="https://www.gclub.online">บาคาร่า gclub</a> directory and start choosing the best online games casinos you can find.

63. anonymous -- 2018-02-25 10:53
64. anonymous -- 2018-02-26 08:33

MauveTree have a great collection of leather jackets not only for bikers but for everyone. We use finest leather and remarkable stitching that gives our jackets an attractive look. Not only that we have a variety of different products from delicate stunning jewelry to valuable handmade paintings. Hurry up! Visit our website now to avail exclusive discount offers. https://www.mauvetree.com/

65. anonymous -- 2018-02-28 15:00
66. anonymous -- 2018-03-02 15:44

This is an example of a good, understandable for a beginner article, thanks to your detailed comments, it was easy for me to understand this article http://19216811-admin.com/ 192.168.l.l

68. anonymous -- 2018-03-11 16:29
69. Lloyd Flaton -- 2018-03-11 17:39

Really good keep it up man http://animaljamhack.club

70. Kenny Daglish -- 2018-03-11 18:09

You have a great collection of coding, lately been searching a lot for a page like this fortunately i found your page. http://imvucreditshack.club

71. Sara Monero -- 2018-03-11 18:31

Rgb to Hsv conversion its not less important to coding, literally we can say that's one of the most important things in coding http://episodecheats.club

72. Den Bravo -- 2018-03-11 18:32

Good to know about this post, i have been lurking through google a lot for a page like this http://episodehack.club

73. anonymous -- 2018-03-13 10:27

How to get ISO certification is Saudi arabia is became easy with kwikcert. To promote your business market world wide ISO standards will help you. We assist you in the certification process in Saudi Arabia.

http://kwikcert.com/iso-certification-saudi-arabia/

74. sushanth -- 2018-03-13 10:28

Are you looking to advertise your products or services? We are there for you to help in billboards, hoarding,mobile van adverts, digital billboards, and LED hoardings in low cost

http://tecknex.com/billboards(ooh)ads.html

75. anonymous -- 2018-03-15 10:38

thanks For sharing this Superb article.I use this Article to show my assignment in college.it is useful For me Great Work.Thanks For sharing this Superb article. http://www.hghgenf20plus.com/

76. Hadley98 -- 2018-03-15 22:32

Thanks for sharing ! http://www.worldcar-mag.com

77. anonymous -- 2018-03-22 09:53

I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. http://best-penis-pump.com/how-to-get-a-bigger-dick/

78. Ash -- 2018-03-28 12:17

Your blog is accurate info! Thanks for sharing useful info! <a href="https://routerloginweb.net">routerlogin net</a> <a href="http://netgearloginhelp.com">routerlogin</a> <a href="http://arlonetgearsupport.com">arlo router login</a>

79. KateGiselle -- 2018-03-29 23:41

Thanks for the website ! http://www.nourriture-bio.net/

80. porady.elk.pl -- 2018-04-04 09:59

I am looking for and I love to post a comment that "The content of your post is awesome" Great work https://porady.elk.pl/

81. SaraDeville -- 2018-04-07 17:48

Thanks for this awesome article! http://musicallycrown.club

82. EmileAndo -- 2018-04-09 20:36

Thanks for this great opinion on coding, I am a huge fan of those codes https://www.psnarea.com

83. faulaniakbar -- 2018-04-12 15:59

So whether your child is learning English for the very first time or is almost fluent, our unique approach will give them all the individual attention and opportunities they need to express themselves in a relaxed and supportive atmosphere. https://medium.com/@jagonyaobatherbal/pengobatan-penyakit-hipertiroid-dengan-cara-alami-7c1f0ec023e2

84. anonymous -- 2018-04-17 02:52

People throughout the world appreciate Kohinoor XL as it lengthens the muscle of male organ, provides extended pleasure at night, and also act as a natural aphrodisiac. Due to the herbal ingredients, and no side effect result, it is recommended by the healthcare experts. It is also widely used by the men for strength and vitality enhancement. http://www.jagonyaobatherbal.com/2018/04/14/cara-menghilangkan-benjolan-di-alat-kelamin-pria-dengan-cepat/

85. anonymous -- 2018-04-18 08:48

So whether your child is learning English for the very first time or is almost fluent, our unique approach will give them all the individual attention and opportunities they need to express themselves in a relaxed and supportive atmosphere http://www.tanamanobatherbal.org/mengenal-5-bahaya-varises-pada-wanita-hamil/.

86. wordsdoctorate -- 2018-04-19 14:49

Thank you for sharing such a informative information with us. Keep on sharing the blog like this. https://www.wordsdoctorate.com/phd/ Thesis writing service https://www.wordsdoctorate.com/ phd thesis writing services https://www.wordsdoctorate.com/dissertation-writing-services/ Dissertation Writing Services https://www.wordsdoctorate.com/journal-papers Research paper Writing Service

Add New Comment