How to Mask an image using Numpy/OpenCV?

前端 未结 4 1689
别跟我提以往
别跟我提以往 2020-12-14 22:32

I have an image I load with:

im = cv2.imread(filename)

I want to keep data that is in the center of the image. I created a circle as a mas

4条回答
  •  误落风尘
    2020-12-14 22:58

    circle is just a 2D array with 1.0s and 0.0s. Numpy needs help to understand what you want to do with the third dimension of your im so you must give it an extra axis and then your line would work.

    masked_data = im * circle[..., np.newaxis]
    

    But note that the masking is simply setting the color to (0, 0, 0) for things outside the circle according to your code if the image lacks an alpha-channel.

    However you have another potential problem: circle will be of the default data-type (which probably will be float64 or float32. That's not good for your image, so you should change the line where you create circle to

    circle = np.zeros((height, width), dtype=im.dtype)
    

提交回复
热议问题