GreycLab / CImg

The CImg Library is a small and open-source C++ toolkit for image processing
http://cimg.eu
Other
1.46k stars 278 forks source link

Alpha-Aware Resize #409

Closed Reptorian1125 closed 4 months ago

Reptorian1125 commented 5 months ago

One of my next attempt at touching CImg,h is implementing alpha-aware resize. That's doable in G'MIC, but the code to do that is resize using average interpolation, split the alpha from color, scale alpha from 0-255 to 0-1, divide color by alpha, re-scale the alpha, append them together. That could be a command without having to do this, but I wanted to do a new command via CImg.h and editing gmic.cpp(?) just to trim some time off (See commentary below) and I'd like that to complete my Mosaic refactor. I can't say I'm satisfied with the execution time via my own G'MIC implementation yet, and I'm thinking it can be noticeably faster.

So, my goal is to have a built-in command which isn't a new function that enables all of that at once.

At the moment, I am studying lines close to this:

//! Resize image to new dimensions \newinstance.

Just so that I can understand it and then make my own implementation.

The plan is to first loop over all of the alpha-channel. Find the weighing factor. And then the color is calculated by multiplying the color by weighing factor of alpha multiplied by alpha. Then insert the result in the resized image. I do wonder if it'll be faster to have a C++ code that stores positions, and amount of alpha value, then use those to find the new value of color which was the main reason I was thinking to touch Cimg.h.

You can see a bit of math here.

# C = Color
# NC = New Color Value
# A = Alpha
# NA = New Alpha Value
# SA= Sum of Alpha
# WF = Weighing Factor

C = 85,255,55
A = 5,100,150

SA =255
WF = 1 / SA = 0.0038461538461538464
NA = 255 / 3 = 85

# To calculate NC, for each color, multiply the value of color by the corresponding alpha value. Multiply the resulting value by the weighing factor. Then, add them altogether

NC = sum(85*5*WF, 255*100*WF, 55*150*WF) =>134.01960784313727

So therefore, the new pixel value is [ 134.01960784313727 , 85 ] .
dtschump commented 5 months ago

Hello @Reptorian1125 ,

I have two things to say about this:

That's being said, of course, you can have fun figuring out how to add native things to CImg/G'MIC if you like, even make your own forks of CImg/G'MIC, which is very instructive. But there's almost no chance of this kind of functionality being integrated into the official CImg/G'MIC packages, especially if you can do the same thing with a custom G'MIC command.