Home > Software engineering >  **Save Image with added mask in python**
**Save Image with added mask in python**

Time:03-12

I'm trying to save an image on which I added a white mask on all the interest areas. But for some reason, It doesn't save the final image and it's not returning any error message. How can I save my image with the mask?

import cv2
import numpy as np


image = cv2.imread('C:/Users/Desktop/testim.png') 
gray_scale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
# Set threshold level 

Dark = 10 

coords = np.column_stack(np.where(gray_scale < Dark)) 

print("xy:\n", coords)

mask = gray_scale < Dark

# Color the pixels in the mask 

image[mask] = (255, 255, 255) 

cv2.imshow('mask', image) 
cv2.waitKey()

#save new image with the added mask to directory 
if not cv2.imwrite(r'./mask.png', image):
     raise Exception("Could not write image")

CodePudding user response:

I think it relates to several typos in the program. After fixing them everything works quite nicely.

import cv2
import numpy as np


image = cv2.imread('/content/test.png') 
gray_scale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
# Set threshold level 

Dark = 10 

coords = np.column_stack(np.where(gray_scale < Dark)) 

# print("xy:\n", coords)

mask = gray_scale < Dark

# Color the pixels in the mask 

image[mask] = (255, 255, 255) 
# cv2.imshow('mask', image) 
cv2.waitKey()

if not cv2.imwrite(r'./mask.png', image):
     raise Exception("Could not write image")

image before manipulationenter image description here

image after manipulationenter image description here

CodePudding user response:

. in a path stands for the Current Working Directory.

That may not be the same directory that contains the script.

Check the CWD using

print("CWD:", os.getcwd())

There you will find your image file.

  • Related