def detect(self, thresh): # 图像大小处理 self.resized = imutils.resize(thresh, width=300) # 将图片的宽度设为300px self.ratio = self.resized.shape[0] / float(self.resized.shape[0]) self.cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) self.cnts = imutils.grab_contours(self.cnts) sd = ShapeDetector() for c in self.cnts: # 获得图形的矩 M = cv2.moments(c) cX = int((M["m10"] / M["m00"]) * self.ratio) cY = int((M["m01"] / M["m00"]) * self.ratio) # 根据多边形点集个数,获得图形的名称 shape = sd.detect(c) # 画出图形的形状并且打印名称 c = c.astype("float") c *= self.ratio c = c.astype("int") # 画出轮廓 -1为画出所有的轮廓,0为只划出一个,1,2,3以此类推,(0,255,0)为划线的颜色,2为固定参数 cv2.drawContours(self.frameArray, [c], -1, (0, 255, 0), 2) # 写出名称 cv2.putText(self.frameArray, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) cv2.imshow("Image", self.frameArray) cv2.waitKey(0)
def find_shapes(img): cnts = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) sd = ShapeDetector() for c in cnts: # Calculate center M = cv2.moments(c) cX = int((M["m10"] / M["m00"]) * ratio) cY = int((M["m01"] / M["m00"]) * ratio) # Detect shape shape = sd.detect(c) # scale contours back up to original image size c = c.astype("float") c *= ratio c = c.astype("int") cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
def main(color, shape): notalign = True aligned = False ardunioData = serial.Serial('COM3', 9600) right = '0' left = '1' up = '2' down = '3' laser = '4' fire = '5' frame = ShapeDetector.FrameCapure() while aligned == False: ShapeDetector.ColorShapeReader(color) image = ShapeDetector.ImagewColor(frame) coordinateX, coordinateY = ShapeDetector.ShapeDiscover(image, shape) centerX, centerY = ShapeDetector.FindCenterImage(image) notalign = False if (centerY < coordinateY): notalign = True ardunioData.write(up.encode()) #move up elif (centerY > coordinateY): notalign = True ardunioData.write(down.encode()) #move down elif (centerX < coordinateX): notalign = True ardunioData.write(left.encode()) #move left elif (centerX > coordinateX): notalign = True ardunioData.write(right.encode()) #move right if (notalign == False): aligned = True #end while #now adjust for distance distanceAway = ShapeDetector.DistanceTest(frame, shape) adjustment = ShapeDetector.AdjustTarget(distanceAway) while (adjustment > 0): ardunioData.write(up.encode()) adjustment = adjustment - 1 ardunioData.write(fire.encode()) #FIRE!!! return 0
image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5,5), 0) # a 5x5 kernel is applied # threshold turns image into binary # if intensity of a pixel is larger than 60, # replace the value with 255, which is white in OpenCV intensityThreshold = 60 thresh = cv2.threshold(blurred, intensityThreshold, 255, cv2.THRESH_BINARY)[1] # now find the contours cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] # they change the position in OpenCV3 # defines what shape an object is sd = ShapeDetector() print "// Escape key = Exit; Any other key = Continue //" # process on each contour for cnt in cnts: # object center M = cv2.moments(cnt) cntX = int(M["m10"] / M["m00"]) cntY = int(M["m01"] / M["m00"]) # detect shape type shapeName = sd.detect(cnt) if shapeName is None: shapeName = "" # say where and what the shape is in the console # draw shapes and text cv2.drawContours(image, [cnt], -1, (0,255,0), 2)
required=True, help="Path to the input image") args = vars(parser.parse_args()) #read the image image = cv2.imread(args["image"]) rImage = cv2.imread(args["image"]) ratio = image.shape[0] / float(image.shape[0]) #Preprocess the image grayedImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurredImage = cv2.GaussianBlur(grayedImage, (5, 5), 0) binImage = cv2.threshold(blurredImage, 60, 255, cv2.THRESH_BINARY)[1] #Create a shape detector shapeDetector = ShapeDetector() #returns a set of contours on the shapes. Always use both lines contours = cv2.findContours(binImage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = contours[0] if imutils.is_cv2() else contours[1] for c in contours: #Compute the center of each contour. #moments characterize the shape of an image like area, centroid, #orientation, other statistical properties. Here we can see #the indicies of the array are string keys print(len(c)) moments = cv2.moments(c) cX = int(moments["m10"] / (moments["m00"] * ratio)) if moments["m00"] != 0 else 0
look(gray) lab = cv2.cvtColor(blurred, cv2.COLOR_BGR2LAB) look(lab) thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)[1] look(thresh) # Invert #thresh = cv2.bitwise_not(thresh) #cv2.imshow("image", thresh); cv2.waitKey(0) #cv2.imwrite(sys.argv[2], thresh) # find contours in the thresholded image and initialize the shape detector # (white=object, black=background) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) sd = ShapeDetector() cl = ColourDetector() for c in cnts: # Calculate center of contours M = cv2.moments(c) cX = int((M["m10"] / M["m00"]) * ratio) cY = int((M["m01"] / M["m00"]) * ratio) # Detect shape shape = sd.detect(c) # Label colours color = cl.label(lab, c) # scale contours back up to original image size c = c.astype("float") c *= ratio
frame = cv2.cvtColor(original_frame, cv2.COLOR_BGR2GRAY) frame = cv2.medianBlur(frame, 5) frame = cv2.GaussianBlur(frame, (5, 5), 0) cv2.absdiff(background_image, frame, frame) # frame = cv2.Canny(frame, 80,80) frame = cv2.threshold(frame, 50, 255, cv2.THRESH_BINARY)[1] #wyszukiwanie konturow contours = cv2.findContours(frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = contours[0] if imutils.is_cv2() else contours[1] shape_detector = ShapeDetector() mask = np.ones(frame.shape[:2], dtype="uint8") * 255 for contour in contours: if shape_detector.detect(contour) == 'square': cv2.drawContours(original_frame, [contour], -1, (0, 255, 0), 2) # area = cv2.boundingRect(np.zeros(contour)) cv2.drawContours(mask, [contour], -1, 0, -1) #dodanie do maski konturu kostki mask = cv2.threshold(mask, 100, 255, cv2.THRESH_BINARY_INV)[1] cropped_frame = cv2.bitwise_and( original_frame, original_frame, mask=mask) #wyciecie kostki z oryginalnego obrazu cropped_frame = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2GRAY)
def AnalyseImage(path, outputPath, removeSpace, aproximationFactor=0.04): data = path print("Analysing image at location:" + str(data)) print("Loading image....") # load the image and resize it to a smaller factor so that # the shapes can be approximated better image = cv2.imread(data) #create backup so we can read collor dirrectly from unmodified image backup = image.copy() print("Resizing image") resized = imutils.resize(image, width=2048) ratio = image.shape[0] / float(resized.shape[0]) # convert the resized image to grayscale, blur it slightly, # and threshold it print("Changing colors to grayscale.") gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1] # find contours in the thresholded image and initialize the # shape detector cnts = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) #cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cnts = imutils.grab_contours(cnts) mapData = [] sd = ShapeDetector() # loop over the contours for c in cnts: # compute the center of the contour, then detect the name of the # shape using only the contour M = cv2.moments(c) if M["m00"] == 0: continue #calculate center of object resizedX = int(M["m10"] / M["m00"]) resizedY = int(M["m01"] / M["m00"]) cX = int((M["m10"] / M["m00"]) * ratio) cY = int((M["m01"] / M["m00"]) * ratio) shape = sd.detect(c, aproximationFactor) rValue = int(backup[cY, cX, 2]) gValue = int(backup[cY, cX, 1]) bValue = int(backup[cY, cX, 0]) # multiply the contour (x, y)-coordinates by the resize ratio, # then draw the contours and the name of the shape on the image c = c.astype("float") c *= ratio c = c.astype("int") (x, y), radius = cv2.minEnclosingCircle(c) center = (int(x), int(y)) radius = int(radius) #used for rotation detection # supposadly the last item in returned struct is angle in degrees rect = cv2.minAreaRect(c) rotation = 0.0 if shape is not "circle": rotation = float(rect[-1]) #lets draw rotation boxes box = cv2.boxPoints(rect) box = np.int0(box) im = cv2.drawContours(image, [box], 0, (0, 0, 255), 2) cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.putText(image, shape, center, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) mapData.append({ "shape": shape, "rotation": rotation, # might be unprecise "color": [rValue, gValue, bValue], "scale": radius, "x": cX, "y": cY, }) normalizeData(mapData, removeSpace) with open(outputPath + '.json', 'w') as outfile: json.dump({"Items": mapData}, outfile) #show the image with marked objects cv2.imwrite(outputPath, image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) # a 5x5 kernel is applied # threshold turns image into binary # if intensity of a pixel is larger than 60, # replace the value with 255, which is white in OpenCV intensityThreshold = 60 thresh = cv2.threshold(blurred, intensityThreshold, 255, cv2.THRESH_BINARY)[1] # now find the contours cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[ 1] # they change the position in OpenCV3 # defines what shape an object is sd = ShapeDetector() print "// Escape key = Exit; Any other key = Continue //" # process on each contour for cnt in cnts: # object center M = cv2.moments(cnt) cntX = int(M["m10"] / M["m00"]) cntY = int(M["m01"] / M["m00"]) # detect shape type shapeName = sd.detect(cnt) if shapeName is None: shapeName = "" # say where and what the shape is in the console # draw shapes and text cv2.drawContours(image, [cnt], -1, (0, 255, 0), 2)
ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) resized = imutils.resize(image, width =300) ratio = image.shape[0]/float(resized.shape[0]) #why init this? gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5,5), 0) thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1] cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] sd = ShapeDetector() # loop through all detected contours for c in cnts: M = cv2.moments(c) cX = int((M["m10"] / M["m00"]) * ratio) cY = int((M["m01"] / M["m00"]) * ratio) shape = sd.detect(c) # multiplay the contour by resized ration and draw them back c *= int(ratio) cv2.drawContours(image, [c], -1, (0,255,0),2) cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2) # show the result