dahtah / imager

R package for image processing
GNU Lesser General Public License v3.0
187 stars 43 forks source link

Center of gravity of an image? #90

Closed mconsidine closed 4 years ago

mconsidine commented 5 years ago

I thought I had seen how to accomplish this, but can't find an example. Namely, I'd like to calculate the "center of gravity" of an image. Google fails me, though I thought this info popped out of one of the imager functions.

Can anyone point me to the solution? What I am trying to do is take an image that has a dominant subject (e.g. planet, like Saturn) in front of a background, crop away as much of the background as I can and then make sure the result has it's "center of gravity" located in the middle of an arbitrary sized frame. E.g. a 317x140 image has it's center of gravity put at the center of a 640x480 frame (new pixels would be black). So this is related to my earlier question of how to get a bounding box calculated.

Thank you! mconsidine

dahtah commented 5 years ago

There's a few ways to do this. One is:

xm=mean(im*Xc(im))
ym=mean(im*Yc(im))

Also:

imeval(im, ~ x*.)  %>% mean
#x rescaled to interval [0,1]
imeval(im,~ xs*.) %>% mean

Using tidyverse tools:

library(dplyr)
as.data.frame(im)  %>%  summarise(xm=mean(x*value),ym=mean(y*value))