how to isolate yellow part of the picture and make black other parts?

697 Views Asked by At

This is the image:

This is the image

I want to turn all the colours to black except yellow and tried this code but showing an error can anyone please help?

import cv2 as cv
import numpy as np
img = cv.imread('Screenshot 2022-04-10 at 10.02.19 AM.png',1)
if(img.any() == [255, 255, 0]):
   cv.imshow('image',img);

else:
   ret , thresh1 = cv.threshold(img,500,255,cv.THRESH_BINARY);
cv.imshow("Timg",thresh1);
cv.waitKey(0)
cv.destroyAllWindows()

The error is showing for the if conditional statement. The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

1

There are 1 best solutions below

6
On

Steps: TLDR;

  1. Convert image to LAB color space
  2. Otsu Threshold over b-component
  3. Mask the result over the original image in BGR color space

Code

# read the image in BGR
img = cv2.imread("image_path", 1)

# convert image to LAB color space
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)

# store b-component
b_component = lab[:,:,2]

enter image description here

# perform Otsu threshold
ret,th = cv2.threshold(b_component, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

enter image description here

# mask over original image
result = cv2.bitwise_and(img, img, mask = th)

enter image description here

Details

Why did I do this?

The LAB color space contains 3 channels:

  • L-component: highlights brightness value
  • a-component: represents color values between green and magenta
  • b-component: represents color values between blue and yellow

Since your image comprised of blue, magenta and yellow, I opted for LAB color space. And specifically the b-component because it highlights yellow color