kazar4
kazar4

Reputation: 77

Thresholding Resistor Bands with OpenCV

So I am trying to make a neural network that categorizes resistor strength by recognizing the color bands. Before I get to that step I want to use OpenCV to threshold all the colors except the resistor bands so that it is easier for the neural network to categorize. However I do not know what threshold type is best suited for this.

I tried several ranges of HLS, RGB, and HSV, but they all do not get rid of the background of the resistor.

Note: I have already used contours to get rid of the background, so now all that is left is the resistor with the colored lines on it.

HLS in my case got rid of the colors, but kept the resistor background, as shown in the code below

frame_HLS = cv2.cvtColor(masked_data, cv2.COLOR_BGR2HLS)
frame_threshold = cv2.inRange(frame_HLS, (50, 0, 0), (139, 149, 255))

Here is an image of the original image, and the HLS output

enter image description here enter image description here

So overall, I am just wondering if anyone knows if the other color modes like LUV work well for this, or whether or not I will just have to use contours or other methods to separate them.

Upvotes: 2

Views: 916

Answers (1)

nathancy
nathancy

Reputation: 46660

You're on the right track and color thresholding is a great approach to segmenting the resistor. Currently, the thresholding is performing correctly, you just need to do a few simple steps to remove the background.

I tried several ranges of HLS, RGB, and HSV, but they all do not get rid of the background of the resistor.

To remove the background we can make use of the binary mask that cv2.inRange() generated. We simply use cv2.bitwise_and() and convert all black pixels on the mask to white with these two lines

result = cv2.bitwise_and(original, original, mask=frame_threshold)
result[frame_threshold==0] = (255,255,255)

Here's the masked image of what you currently have (left) and after removing the background (right)

enter image description here enter image description here

import cv2

image = cv2.imread('1.png')
original = image.copy()
frame_HLS = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)
frame_threshold = cv2.inRange(frame_HLS, (50, 0, 0), (139, 149, 255))

result = cv2.bitwise_and(original, original, mask=frame_threshold)
result[frame_threshold==0] = (255,255,255)

cv2.imshow('result', result)
cv2.waitKey()

However I do not know what threshold type is best suited for this.

Right now you're using color thresholding, you could continue using this method and experiment with other ranges in the HLS, RGB, or HSV color space. In all of these cases, you can remove the background by converting in all black pixels on the mask to white. If you decide to pivot to another thresholding method, take a look at Otsu's threshold or Adaptive thresholding which automatically calculates the threshold value.

Upvotes: 1

Related Questions