1

I am writing a program to generate photomosaics and I need the find the average RGB value of an image. I am doing this using distance and numpy as such:

def average_color(image):
    """get the average rgb color of the image"""
    npimg = np.array(image)
    avg = np.round(np.average(npimg,axis=(0,1)))
    return avg

The problem is, for some reason once in a while it produces a numpy.float64 instead of a numpy array. I discovered that the problem came from a weird value of npimg :

  [[234 232 244 236 239 240 240 243 238 242]
 [237 234 235 234 230 231 235 237 240 243]
 [242 239 234 243 248 249 245 238 241 243]
 [246 247 246 252 255 255 252 244 248 246]
 [250 251 250 254 255 255 254 247 251 249]
 [252 253 253 255 255 255 255 253 253 251]
 [253 253 251 254 255 255 254 249 253 251]
 [252 253 250 253 255 255 253 244 252 249]
 [248 245 233 244 246 246 243 228 240 242]
 [240 230 225 233 233 234 227 222 224 234]]

When usually it looks like this:

[[252 228 200]
  [252 228 200]
  [252 228 200]
  [251 227 199]
  [252 228 200]
  [252 228 200]
  [253 229 201]
  [254 230 202]
  [253 230 199]
  [253 230 199]]

Why does it do that and how can I solve it ( can I safely use reshape for this job?)

Hero Yu
  • 11
  • 1
  • 1
    I'm guessing your inout image is greyscale rather than RGB. Have a read here https://stackoverflow.com/a/52307690/2836621 – Mark Setchell Feb 04 '22 at 16:08
  • This does seem to be the case. I am getting an L when print the mode the faulty image that gives me this result. The image I am giving it is actually a slice of photo. I am thinking the problem is the fact that I did not check the image before slicing so it might at some point cut an incomplete piece of image. Is there a way to get rid of this without modifying the slicing part? – Hero Yu Feb 04 '22 at 16:27
  • 1
    Please read the answer I linked to - especially the sentence starting *"Here's the kicker..."* – Mark Setchell Feb 04 '22 at 16:35

0 Answers0