1

This is the code for masking an image (see).

Why does the mask need to be divided by 255? Isn't img0 = mask * img a pixelwise multiplication, so in the middle all the values will be kept (if multiplying by 1 and not divide by 255)

img = np.array(Image.open('input.jpg'))
ones = np.ones((img.shape[0] // 2, img.shape[1] // 2, 3))
zeros = np.zeros(((img.shape[0] // 4, img.shape[1] // 4, 3)))
zeros_mid = np.zeros(((img.shape[0] // 2, img.shape[1] // 4, 3)))
up = np.concatenate((zeros, zeros, zeros, zeros), axis=1)
middle = np.concatenate((zeros_mid, ones, zeros_mid), axis=1)
down = np.concatenate((zeros, zeros, zeros, zeros), axis=1)
mask = np.concatenate((up, middle, down), axis=0)
mask = mask / 255
img0 = mask * img
fig = plt.figure(figsize=(10, 10))
fig.add_subplot(1, 2, 1)
plt.imshow(img)
fig.add_subplot(1, 2, 2)
plt.imshow(img0)
Danny Dan
  • 25
  • 5
  • 1
    Yeah, that makes no sense. OpenCV has values of 0 and 255 in binary (mask) images, so there you’d need to divide by 255. But in your bit of code you shouldn’t. – Cris Luengo May 14 '23 at 16:54
  • 1
    Do note that `img0 = mask * img` leads to a floating-point array, which is typically displayed differently than an 8-bit integer array. You could instead do `img *= mask` your preserve the array’s type. – Cris Luengo May 14 '23 at 16:56
  • Thanks! About OpenCV masks- Namely the binary masks that done with `cv2.bitwise_and`, right? – Danny Dan May 14 '23 at 17:13
  • that is simply a bad site. avoid it, or ALWAYS deal with its content critically. it will be full of mistakes. -- `mask` will already be values from 0 to 1. pushing the factor of `1/255` in there, then multiplying onto `img`, causes `img` to be scales from 0..255 to 0..1 – Christoph Rackwitz May 14 '23 at 17:38

0 Answers0