[PYTHON] Be careful of the type when making an image mask with Numpy

Thing you want to do

If you want to fill out a part of an image or video in black and crop it, create a mask for the image and overlay it.

The original image lena.png Masked image masked_image.png

Failure

Use Numpy to create a mask where the area you want to blacken is 0 and the area you want to crop is 1. When I thought that I could mask by multiplying each element of the matrix, the output was different from what I expected.

h_img, w_img = img.shape[:2]
mask = np.zeros((h_img, w_img, 3))
radius = int(h_img / 2)
center = radius
cv2.circle(mask, (center, center), radius, (1, 1, 1), thickness=-1, shift=0)
masked_img = img * mask

Mask made with Numpy err_mask.png

Masked image (masked_img) err_masked_image.png

Cause and solution

When defining a matrix in Numpy, if you don't specify dtype, it defaults to float64. On the other hand, the image read by imread of opencv is read by CV_8U, CV_16F, CV_32F (usually CV_8U) depending on its brightness. With CV_8U, the Numpy data type supports np.uint8. In other words, in the failed example, the image of CV_8U is masked with float64 type.

When defining a matrix in Numpy, specify the type to np.uint8. did it.

mask = np.zeros((h_img, w_img, 3), dtype=np.uint8) #Specify type as uint8

Masked image masked_image.png

When I try to display the mask as an image, it is pitch black. mask.png

Impressions

It's a rudimentary mistake of data type mismatch, but it took me a while to notice, probably because I've been using only python lately and have less chance to be aware of the type. In the first place, instead of defining it in np.zeros, I should have used np.zeros_like to define the matrix including the image type.

Recommended Posts

Be careful of the type when making an image mask with Numpy
Be careful when differentiating the eigenvectors of a matrix
Solution when the image cannot be displayed with tkinter [python]
Be careful of LANG for UnicodeEncodeError when printing Japanese with Python 3
The story of making Python an exe
The story of making an immutable mold
Be careful when adding an array to an array
Be careful when running CakePHP3 with PHP7.2
Be careful when retrieving tweets at regular intervals with the Twitter API
The story of making a tool to load an image with Python ⇒ save it as another name
Extract the color of the object in the image with Mask R-CNN and K-Means clustering
[Python] Determine the type of iris with SVM
Be careful when working with gzip-compressed text files
[Caution] When creating a binary image (1bit / pixel), be aware of the file format!
Extract the table of image files with OneDrive & Python
Be careful when reading data with pandas (specify dtype)
When reading an image with SimpleITK, there is a problem if there is Japanese in the path
Create a 2D array by adding a row to the end of an empty array with numpy
I tried to find the entropy of the image with python
I tried "gamma correction" of the image with Python + OpenCV
NumPy zeros can be defined even with a size of 0
Master the type in Python? (When should type check be done)
The story of making a question box bot with discord.py
What to do when a part of the background image becomes transparent when the transparent image is combined with Pillow
A method of converting the style of an image while preserving the color
Understand the function of convolution using image processing as an example
Be careful when specifying the default argument value in Python3 series
Become familiar with (want to be) around the pipeline of spaCy
Calculate the similarity between sentences with Doc2Vec, an evolution of Word2Vec
[Statistics] Grasp the image of the central limit theorem with a graph
ZipArchive couldn't be used with the Laravel image launched by ConoHa.
Consider the speed of processing to shift the image buffer with numpy.ndarray
[Pythonista] The story of making an action to copy selected text
Solution when an error occurs when hiding the console screen with PyInstaller
The story of making a module that skips mail with python
A memo when creating an environment that can be debugged with Lambda @ Edge for the time being