Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def contour_img(img_path,thresh=400,std_dev=4, hsv_lower=[22, 30, 30], hsv_upper=[45, 255, 255]):
- """Returns the name of the saved contour PNG image that will be sent for OCR thru API"""
- contoured_img = "contoured_"+os.path.basename(img_path).split(".")[0]+".png"
- image = cv2.imread(img_path)
- # rgb to HSV color spave conversion
- hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
- HSV_lower = np.array(hsv_lower, np.uint8) # Lower HSV value
- HSV_upper = np.array(hsv_upper, np.uint8) # Upper HSV value
- frame_threshed = cv2.inRange(hsv_img, HSV_lower, HSV_upper)
- # find connected components
- _, contours, hierarchy, = cv2.findContours(frame_threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
- # Draw contours around filtered objects
- OutputImg = image.copy()
- cnt_lens = [cv2.contourArea(x) for x in contours]
- klist = cnt_lens
- avglatlist = range(0,len(cnt_lens))
- klist_np = np.array(klist).astype(np.float)
- avglatlist_np = np.array(avglatlist).astype(np.float)
- # klist_filtered = klist_np[(abs(klist_np - np.mean(klist_np))) > (std_dev * np.std(klist_np))]
- avglatlist_filtered = avglatlist_np[(abs(klist_np - np.mean(klist_np))) > (std_dev * np.std(klist_np))]
- while len(avglatlist_filtered)==0:
- if std_dev<1.5:
- return False
- break
- std_dev=std_dev-0.5
- avglatlist_filtered = avglatlist_np[(abs(klist_np - np.mean(klist_np))) > (std_dev * np.std(klist_np))]
- max_thresh = max(cnt_lens)
- mask = np.zeros_like(image) # Create mask where white is what we want, black otherwise
- out = np.zeros_like(image) # Extract out the object and place into output image
- for c in avglatlist_filtered:
- # # remove noise objects having contour length threshold value
- cnt = contours[int(c)]
- if len(cnt) > thresh:
- expand_cnt = expand_contour(cnt,expand_rate_x=1.02,expand_rate_y=1.04)
- # smooth_cnt = smoothen_contour(expand_cnt)
- epsilon = 0.001*cv2.arcLength(cnt,True)
- print "Epsilon", epsilon
- smooth_cnt = cv2.approxPolyDP(expand_cnt, epsilon, False)
- # cust_smooth_cnt = custom_smoothen_cnt(cnt)
- cv2.drawContours(OutputImg, [cnt], 0, (0, 0, 50), 1)
- cv2.drawContours(OutputImg, [expand_cnt], 0, (0, 0, 255), 2)
- cv2.drawContours(OutputImg, [smooth_cnt], 0, (255, 0, 0), 2)
- # cv2.drawContours(OutputImg, [smooth_cnt], 0, (0, 255,0), 1)
- cv2.drawContours(mask, [smooth_cnt], 0, (255,255,255), -1) # Draw filled contour in mask
- cv2.drawContours(mask, [expand_cnt], 0, (255, 255, 255), -1) # Draw filled contour in mask
- # hull = cv2.convexHull(cnt)
- out[mask == 255] = image[mask == 255]
- out[mask == 0] = 255
- imgray = cv2.cvtColor(out, cv2.COLOR_BGR2GRAY)
- #save contoured image to display
- j = Image.fromarray(imgray)
- j.save(contoured_img)
- cv2.imwrite("col_"+contoured_img,OutputImg)
- return contoured_img
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement