masking bgr image using a 2d mask

  • Last Update :
  • Techknowledgy :

Try to use a mask with the same shape as the image (actually, this will be a 3D mask). After generating your image_mask, do

# create mask with same dimensions as image
mask = numpy.zeros_like(image)

# copy your image_mask to all dimensions(i.e.colors) of your image
for i in range(3):
   mask[: ,: , i] = image_mask.copy()

# apply the mask to your image
masked_image = image[mask]

Maybe this alternative approach would be easier in similar cases:

image[image_mask,: ] = np.nan

Suggestion : 2

To learn how to perform image masking with OpenCV, just keep reading.,You can master Computer Vision, Deep Learning, and OpenCV - PyImageSearch,We’ll then implement a Python script to mask images with OpenCV.,Let’s learn how to apply image masking using OpenCV!

Luckily, OpenCV is pip-installable:

$ pip install opencv - contrib - python

Your project folder should look like the following:

$ tree.--dirsfirst
   .├──adrian.png└── opencv_masking.py

0 directories, 2 files

Open the opencv_masking.py file in your project directory structure, and let’s get to work:

#
import the necessary packages
import numpy as np
import argparse
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type = str,
   default = "adrian.png",
   help = "path to the input image")
args = vars(ap.parse_args())

Let’s look at another example, but this time using a non-rectangular mask:

# now,
let 's make a circular mask with a radius of 100 pixels and
# apply the mask again
mask = np.zeros(image.shape[: 2], dtype = "uint8")
cv2.circle(mask, (145, 200), 100, 255, -1)
masked = cv2.bitwise_and(image, image, mask = mask)

# show the output images
cv2.imshow("Circular Mask", mask)
cv2.imshow("Mask Applied to Image", masked)
cv2.waitKey(0)

From there, open a shell and execute the following command:

$ python opencv_masking.py

Suggestion : 3

MathWorks is the leading developer of mathematical computing software for engineers and scientists.,Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location., Link × Direct link to this comment https://www.mathworks.com/matlabcentral/answers/341305-how-to-impose-binary-mask-on-rgb-color-image#comment_455827 Cancel Copy to Clipboard , Link × Direct link to this comment https://www.mathworks.com/matlabcentral/answers/341305-how-to-impose-binary-mask-on-rgb-color-image#comment_455653 Cancel Copy to Clipboard

Your mask is not binary. It's showing severe jpeg artifacts. It may even be color or uint8. You need to make it a binary image:

mask = mask(: ,: , 1) > 128;