#Modification of code https://github.com/AhadCove/LegoBlobDetection #To save individual detected objects import cv2 import numpy as np #read image in grayscale img = cv2.imread(r'F:\PetProject\LegoKeypoint\30-legos.jpg',cv2.IMREAD_GRAYSCALE) outputdirectory = r'F:\PetProject\SubImage' #image height / width based on dimensions height = np.size(img, 0) width = np.size(img, 1) detector = cv2.SimpleBlobDetector_create() #Detect the blobs in image keypoints = detector.detect(img) print(len(keypoints)) j = 0 for keypoint in keypoints: x = int(keypoint.pt[0]) y = int(keypoint.pt[1]) #Adjust the centre key point to start of x x = x-20 #Adjust y to cover complete object y = y-50 s = keypoint.size octave = keypoint.octave print(x,y) print(height,width) #if height and width exceeds original image dimension skip this step #70 is rough size of the blob based on analysis #check for margins and size before extracting the regions if(y+70 < height and x+70 < width and x > 0 and y > 0): newImage=img[y:y+70,x:x+70] object_file_name = outputdirectory + str('\\') + str(j) + ".jpg" j = j+1 cv2.imwrite(object_file_name, newImage) #draw detected keypoints imgkeypoints = cv2.drawKeypoints(img,keypoints,np.array([]),(0,0,255),cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) #Display found keypoints cv2.imshow("keypoints",imgkeypoints) cv2.imwrite(r"F:\PetProject\LegoKeypoint\square_circle_opencv.jpg", img) cv2.waitKey(0) cv2.destroyAllWindows()