In: Computer Science
How can I convert inRange in cv2 to PIL? For example, I already have mask = cv2.inRange(img, array1, array2) but I'm trying to keep everything in PIL. Any ideas would be appreciated!
We generally use inRange() to apply a mask over an image(which is in np parray) and give the lower and upper arrays to the function to get the mask. Inorder to convert it into PIL we have a method called fromarray in PIL.Image. It will convert into PIL_Image. A very important note is that, when we use cv2, the image will be in BGR color convention. So to convert the inRange to PIL, we have to convert the image from BGR to RGB first since PIL follows RGB color convention. I suggest you go through the following code to get a clear understanding.
import cv2
import numpy as np
from PIL import Image #Import required libraries
img=cv2.imread('/content/test2.png') #We take a test image
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #Convert the BGR image to RGB color convention
lower = np.array([170,50,50]) #lower array
upper = np.array([180,255,255]) #upper array
mask=cv2.inRange(img,lower,upper) #using inRange to get the mask
PIL_Image=Image.fromarray(mask) #convert the mask to PIL_Image
PIL_Image.save('final.jpg') #Save the PIL_Image