title: How can I efficently pad an RGB numpy array with the median of the image?
body: <p>I have RGB images which have already been rescaled so that the longer edge becomes 256 pixels, now I want to pad the border with the median RGB values of that image so the resulting image is always 256x256 pixels.</p>
  <p>This code already works, but I am sure there could be a simpler more elegant way to do this:</p>
  <pre><code>img = loadAndFitImage(filePath, maxSideLength=256, upscale=True)
  shp = img.shape
  #the shp in this case is typically (256,123,3) or (99,256,3)
  
  leftPad = (256 - shp[0]) / 2
  rightPad = 256 - shp[0] - leftPad
  topPad = (256 - shp[1]) / 2
  bottomPad = 256 - shp[1] - topPad
  
  # this part looks like there might be a way to do it with one median call instead of 3:
  median = (np.median(img[:, :, 0]),np.median(img[:, :, 1]),np.median(img[:, :, 2]))
  
  img = np.lib.pad(img, ((leftPad,rightPad),(topPad,bottomPad),(0,0)),
   'constant',constant_values=0)
  
  if leftPad &gt; 0:
      img[:leftPad,:,0].fill(median[0])
      img[:leftPad,:,1].fill(median[1])
      img[:leftPad,:,2].fill(median[2])
  if rightPad &gt; 0:
      img[-rightPad:,:,0].fill(median[0])
      img[-rightPad:,:,1].fill(median[1])
      img[-rightPad:,:,2].fill(median[2])
  if topPad &gt; 0:
      img[:,:topPad,0].fill(median[0])
      img[:,:topPad,1].fill(median[1])
      img[:,:topPad,2].fill(median[2])
  if bottomPad &gt; 0:
      img[:,-bottomPad:,0].fill(median[0])
      img[:,-bottomPad:,1].fill(median[1])
      img[:,-bottomPad:,2].fill(median[2])
  </code></pre>
  <p>Edit (Additional Info):</p>
  <ul>
  <li><p>This is how the final result should look like:</p>
  </li>
  <li><p><a href="https://i.stack.imgur.com/ZmlIH.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ZmlIH.jpg" alt="Desired:" /></a></p>
  </li>
  <li><p>This is how it should not look like (median per column):</p>
  </li>
  <li><p><a href="https://i.stack.imgur.com/O50dD.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/O50dD.jpg" alt="Undesired:" /></a></p>
  </li>
  </ul>