Interactive Color Detection in Jupyter by using OpenCv

 Interactive Color Extraction in Jupyter by using OpenCv

Before you read start coding make sure you have install ipywidgets , opencv libraray
to install ipywidgets  type (anaconda cmd) : pip install ipywidgets

Steps for color extraction:
  1. Select any image as per your requirement
  2. Create a function f and define input variable as show in video
  3. Convert your image into rgb first (if you are going to show by using cv2 skip this step)
    Note : cv2 stores image in BGR format where matplot store image in RGB format that is the reason we have convert it into RGB format
  4. Now convert the image into HSV format (but why )
  5. Now we have to define upper and lower limits of HSV so that we can extract a particular color (Why limits and how it works)
  6. We can use slider (ipywidgets is use to make it) to extract a particular in opencv . But we are using matplotlib to show our image in jupyter

Image as input : 

import cv2
import numpy as np
from ipywidgets import *
import matplotlib.pyplot as plt

def f (hMin ,hMax ,Smin,Smax ,Vmin,Vmax):
    img1 = cv2.imread('p.png')
    img = cv2.cvtColor(img1 ,cv2.COLOR_BGR2RGB)  #in matplot image show in rgb format in cv2 it show in bgr format remeber this else you will face problem
    hsv = cv2.cvtColor(img,cv2.COLOR_RGB2HSV)# if you are going to use cv2 to show image then cv2.COLOR_BGR2HSV 
    Lhsv = np.array([hMin,Smin,Vmin])
    Uhsv = np.array([hMax ,Smax,Vmax])
    mask = cv2.inRange(hsv,Lhsv ,Uhsv)
    r = cv2.bitwise_and(img,img,mask =mask)
interactive_plot = interactive(f,hMin=(0,179),hMax = (0,179),Smin = (0,250),Smax =(0,255),Vmin=(0,255),Vmax=(0,255))


Output :

Post a Comment