简体   繁体   中英

How to mask an image in a square shape?

I am trying to mask a square shape out of a rectangular image. Those area out of square shape will be painted white. I write code as below.

photo_data = imageio.imread('./demo/dog.jpg')
total_rows,total_columns,layer=photo_data.shape
X,Y=np.ogrid[:total_rows,:total_columns]
center_rows=total_rows/2
center_columns=total_columns/2
upper_mask=X-center_rows>500
low_mask=X-center_rows<-500
left_mask=Y-center_columns>500
right_mask=Y-center_columns<-500
final_mask=np.logical_and(upper_mask,low_mask,left_mask,right_mask)
photo_data[final_mask]=0
plt.figure(figsize=(15,15))
plt.imshow(photo_data)

I guess np.logical_and cannot handle array with different number size. How to resolve this problem?

I think that you make things a bit more complicated than you need to. Conceptually, I think that you need to do something along these lines:

photo_data = imageio.imread('./demo/dog.jpg')
total_rows,total_columns,layer=photo_data.shape
mask_size = 500
photo_data[total_rows/2-mask_size/2:total_rows/2+mask_size/2,
    total_columns/2-mask_size/2:total_columns/2+mask_size/2,
    :] = 0
plt.figure(figsize=(15,15))
plt.imshow(photo_data)

EDIT:

I assume that there are even more elegant ways of performing this, but one way that I personally like is to use numpys elemet wise multiplication to apply the mask:

import numpy as np

photo_data = imageio.imread('./demo/dog.jpg')
total_rows,total_columns,layer=photo_data.shape
mask_size = 500

mask = np.zeros(photo_data.shape)
mask[total_rows/2-mask_size/2:total_rows/2+mask_size/2,
    total_columns/2-mask_size/2:total_columns/2+mask_size/2,
    :] = 1
photo_data = photo_data * mask
plt.figure(figsize=(15,15))
plt.imshow(photo_data)

Instead of

np.logical_and(upper_mask,low_mask,left_mask,right_mask)

you can use

upper_mask & low_mask & left_mask & right_mask

but actually you need OR for your task, so correct way is to use:

upper_mask | low_mask | left_mask | right_mask

Then you code works well!

Full corrected code down below:

Try it online!

import imageio, numpy as np, matplotlib.pyplot as plt

photo_data = imageio.imread('https://i.stack.imgur.com/lb6U1.jpg')
total_rows,total_columns,layer=photo_data.shape
X,Y=np.ogrid[:total_rows,:total_columns]
center_rows=total_rows/2
center_columns=total_columns/2
upper_mask=X-center_rows>100
low_mask=X-center_rows<-100
left_mask=Y-center_columns>100
right_mask=Y-center_columns<-100
final_mask=upper_mask | low_mask | left_mask | right_mask
photo_data[final_mask]=0
plt.figure(figsize=(7,5))
plt.imshow(photo_data)
plt.show()

Input:

img0

Output:

图片1

Also if you want white surroundings instead of black then replace

photo_data[final_mask]=0

with

photo_data[final_mask]=255

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM