def calc_contours(image_path): img = cv2.imread(image_path) # Apply bilateral filter img_bilateral = cv2.bilateralFilter(img, 9, 75, 75) # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply thresholding to remove text and noise _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY) # Apply ROI masking to exclude non-graph regions mask = np.zeros_like(thresh) mask[50:400, 100:700] = 255 masked_thresh = cv2.bitwise_and(thresh, mask) # Apply edge detection using the Canny algorithm edges = cv2.Canny(gray, 100, 200) # Apply horizontal line detection using HoughLinesP lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=250, maxLineGap=15) horizontal_lines = [] for line in lines: x1, y1, x2, y2 = line[0] if abs(y1 - y2) < 5: # Check if the line is horizontal horizontal_lines.append(line) # Draw the detected lines on the image for line in horizontal_lines: x1, y1, x2, y2 = line[0] # cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255), 2) # Find contours in the image contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Filter out unwanted contours based on contour area and aspect ratio bars = [] for cnt in contours: area = cv2.contourArea(cnt) x, y, w, h = cv2.boundingRect(cnt) aspect_ratio = float(w) / h if area > 7 and aspect_ratio > 5 and aspect_ratio < 50000: bars.append(cnt) ###### 2 consecutive element from the bars represent single contour only ###### and we will consider only one of them, so we will filter out odd index elemnts from the "bars" def filter_bars(bars): lst = [] for i in range(len(bars)): if(i%2==1): lst.append(bars[i]) return lst bars = filter_bars(bars) # Draw the remaining contours on the image cv2.drawContours(img, bars, -1, (255, 255, 0), 2) # Show the image cv2_imshow(img) return bars
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter