HTML5 Canvas image contrast

前端 未结 7 1343
情书的邮戳
情书的邮戳 2020-12-13 04:51

I\'ve been writing an image processing program which applies effects through HTML5 canvas pixel processing. I\'ve achieved Thresholding, Vintaging, and ColorGradient pixel m

相关标签:
7条回答
  • 2020-12-13 05:24

    I found out that you have to use the effect by separating the darks and lights or technically anything that is less than 127 (average of R+G+B / 3) in rgb scale is a black and more than 127 is a white, therefore by your level of contrast you minus a value say 10 contrast from the blacks and add the same value to the whites!

    Here is an example: I have two pixels with RGB colors, [105,40,200] | [255,200,150] So I know that for my first pixel 105 + 40 + 200 = 345, 345/3 = 115 and 115 is less than my half of 255 which is 127 so I consider the pixel closer to [0,0,0] therefore if I want to minus 10 contrast then I take away 10 from each color on it's average Thus I have to divide each color's value by the total's average which was 115 for this case and times it by my contrast and minus out the final value from that specific color:

    For example I'll take 105 (red) from my pixel, so I divide it by total RGB's avg. which is 115 and times it by my contrast value of 10, (105/115)*10 which gives you something around 9 (you have to round it up!) and then take that 9 away from 105 so that color becomes 96 so my red after having a 10 contrast on a dark pixel.

    So if I go on my pixel's values become [96,37,183]! (note: the scale of contrast is up to you! but my in the end you should convert it to some scale like from 1 to 255)

    For the lighter pixels I also do the same except instead of subtracting the contrast value I add it! and if you reach the limit of 255 or 0 then you stop your addition and subtraction for that specific color! therefore my second pixel which is a lighter pixel becomes [255,210,157]

    As you add more contrast it will lighten the lighter colors and darken the darker and therefore adds contrast to your picture!

    Here is a sample Javascript code ( I haven't tried it yet ) :

    var data = imageData.data;
    for (var i = 0; i < data.length; i += 4) {
     var contrast = 10;
     var average = Math.round( ( data[i] + data[i+1] + data[i+2] ) / 3 );
      if (average > 127){
        data[i] += ( data[i]/average ) * contrast;
        data[i+1] += ( data[i+1]/average ) * contrast;
        data[i+2] += ( data[i+2]/average ) * contrast;
      }else{
        data[i] -= ( data[i]/average ) * contrast;
        data[i+1] -= ( data[i+1]/average ) * contrast;
        data[i+2] -= ( data[i+2]/average ) * contrast;
      }
    }
    
    0 讨论(0)
提交回复
热议问题