0

I am taking an RGB image as an input in Python which it obviously converts into 2D numpy array. I would like to replace only a window/part of an image by making it totally white (or replacing it with a 2D numpy array having values of only 255).

Here's what I tried:

img[i:i+r,j:j+c] = (np.ones(shape=(r,c))) * 255

r,c is my window size (128*128) and my input image is of RGB channel. It throws an error:

ValueError: could not broadcast input array from shape (128,128) into shape (128,3)

Note: I would like my final output image to be in RGB channel with specific parts replaced by white windows. I am using Python 3.5.

user529295
  • 189
  • 2
  • 11
  • 1
    Please double check the shape of `img`. The error says that your image has the shape (128,3) and you are trying to apply a window of (128,128), which is not possible. – Kapil May 28 '18 at 06:41
  • You are probably taking the RGB image input incorrectly. Please provide your image reading code for further help. – Kapil May 28 '18 at 06:43
  • [PD](https://stackoverflow.com/q/765736/5033247) – Smart Manoj May 28 '18 at 07:01

1 Answers1

0

You can do it like this:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Numpy array containing 640x480 solid blue image
solidBlueImage=np.zeros([480,640,3],dtype=np.uint8)
solidBlueImage[:]=(0,0,255)

# Make a white window
solidBlueImage[20:460,200:600]=(255,255,255)

# Save as PNG
img=Image.fromarray(solidBlueImage)
img.save("result.png")

enter image description here

Essentially, we are using numpy indexing to draw over the image.


Or like this:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Numpy array containing 640x480 solid blue image
solidBlueImage=np.zeros([480,640,3],dtype=np.uint8)
solidBlueImage[:]=(0,0,255)

# Make a white array
h,w=100,200
white=np.zeros([h,w,3],dtype=np.uint8)
white[:]=(255,255,255)

# Splat white onto blue
np.copyto(solidBlueImage[20:20+h,100:100+w,],white)

# Save as PNG
img=Image.fromarray(solidBlueImage)
img.save("result.png")

enter image description here

Essentially, we are using numpy's copyto() in order to paste, (or composite or overlay), one image into another.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432