Search code examples
python-3.xopencvmasking

Masking colors using opencv


I tried to mask image by its color using opencv.

import cv2
import numpy as np
import matplotlib.pyplot as plt

After importing libraries, I load the image

img = cv2.imread('gmaps.jpg')
image = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(image);

Turn the color into hsv

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
plt.imshow(hsv);

Masking process

low_orange = np.array([44, 6, 100])
high_orange = np.array([44, 24, 99])
masking = cv2.inRange(hsv,low_orange, high_orange)
plt.imshow(masking);

The result isn't what I expected.

Image : Real image

Result : Result

EDIT: I want to mask the building only. Instead I got the result of masking all of the frame.


Solution

  • Using my answer from here I manage to extract the right values for you

    enter image description here

    Code:

        frame = cv2.imread("Xv6gx.png")
        blurred_frame = cv2.GaussianBlur(frame, (5, 5), 0)
        hsv = cv2.cvtColor(blurred_frame, cv2.COLOR_BGR2HSV)
    
        lower = np.array([4, 0, 7])
        upper = np.array([87, 240, 255])
        mask = cv2.inRange(hsv, lower, upper)
        contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    
        for contour in contours:
            area = cv2.contourArea(contour)
            if area > 5000:
                 # -- Draw Option 1 --
                 cv2.drawContours(frame, contour, -1, (0, 255, 0), 3)
    
                 # -- Draw Option 2--
                 # rect = cv2.boundingRect(contour)
                 # x, y, w, h = rect
                 # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
    
        cv2.imshow("Mask", mask)
        cv2.imshow("Frame", frame)
    
        cv2.waitKey(0)
    

    Final Results: