I want to detect the circlip in the fixture. if circlip is not present it should give a message "circlip not present".
in this case, though my circlip is blue, i used blue colour detection. But i want to know what can be done if the circlip is black in colour as it is most difficult to recognize the circlip in black colour.
Please find the input image:
here circlip is not present
please find the code for circlip detection. also i want to know what can i do with masked image if circlip is detected to print "ok" message.
import cv2
import numpy as np
import imutils
from imutils import contours
img = cv2.imread('BALL1.jpg')
img=cv2.resize(img,(1000,640))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_range = np.array([110,50,50])
upper_range = np.array([130,255,255])
mask = cv2.inRange(hsv, lower_range, upper_range)
cv2.imshow('image', img)
cv2.imshow('mask', mask)
while(True):
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
please find the screenshot of the output for the same.
i/p image
mask image
I applied binarization but not able to get clear result out of it. please find the code and ss of the output.
import cv2
# read the image file
img = cv2.imread('BALL1.jpg', 2)
img=cv2.resize(img,(1000,640))
ret, bw_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# converting to its binary form
bw = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow("Binary", bw_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
below is the ss of the output retreived
CodePudding user response:
Binarization applied to the saturation component gives interesting results.
vs.
But the circlip needs to remain tinted.
CodePudding user response:
The solution provided by @YvesDaoust gives good insights into solving the problem.
Thresholding on Saturation channel as suggested by @YvesDaoust, followed by Morphological closing, and
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np
img = cv2.imread("input2.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
s = hsv[...,1]
th = 100
s[s<th]=0
op = cv2.MORPH_CLOSE
morph_elem = cv2.MORPH_ELLIPSE
morph_size = 5
element = cv2.getStructuringElement(morph_elem, (2*morph_size 1, 2*morph_size 1), (morph_size, morph_size))
mph = cv2.morphologyEx(s, op, element)
# Reference: https://stackoverflow.com/a/47057324
def lcc (image):
image = image.astype('uint8')
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
sizes = stats[:, -1]
max_label = 1
max_size = sizes[1]
for i in range(2, nb_components):
if sizes[i] > max_size:
max_label = i
max_size = sizes[i]
img2 = np.zeros(output.shape)
img2[output == max_label] = 255
img2 = img2.astype(np.uint8)
return img2
mask = lcc(mph)
thresh = 20000000
if np.sum(mask) < thresh:
print("circlip not present")
res = img
else:
res = cv2.bitwise_and(img,img,mask = mask)
cv2.namedWindow("img", cv2.WINDOW_NORMAL)
cv2.imshow("img", res)
cv2.waitKey(0)