Extract Graph Data from image using the openCV?


I’m pretty new to both python and openCV. I just need it for one project. Users take picture of ECG with their phones and send it to the server I need to extract the graph data and that’s all.
Here’s some code which tries to isolate the graph by making the lines white (It works on the cropped image) Still leaves some nasty noises and inacurate polygons at the end some parts are not detected :

import cv2
import numpy as np

img = cv2.imread('image.jpg')

kernel = np.ones((6,6),np.uint8)
dilation = cv2.dilate(img,kernel,iterations = 1)

gray = cv2.cvtColor(dilation, cv2.COLOR_BGR2GRAY)
ret,gray = cv2.threshold(gray,160,255,0)
gray2 = gray.copy()
mask = np.zeros(gray.shape,np.uint8)

contours, hier = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    if cv2.contourArea(cnt) > 400:
        approx = cv2.approxPolyDP(cnt,
                                  0.005 * cv2.arcLength(cnt, True), True)
        if(len(approx) >= 5):
            cv2.drawContours(img, [approx], 0, (0, 0, 255), 5)
res = cv2.bitwise_and(gray2,gray2,mask)

Now I need to make it better. I found most of the code from different places and attached them togheter.


For example here if I use anything other than 6,6 I’m in trouble :frowning:


I found 160 255 by tweaking and all other hardcoded values in my code what if the lighting on another picture is different and these values won’t work anymore?

And other than this I don’t still get the result I want some polygons are attached by two different lines from bottom and top!

I just want one line to go from beggining to the end.

Please guide me to tweak and fix it for more general use.


findContours expects white contours on black bg, so you should use the THRESH_BINARY_INV flag (or manually ~img)
(right now, it finds the light pixels next to your line, that’s also why you have it on both sides of it – bad !)

THRESH_OTSU will find an optimal value automatically

it’s also a good idea, to visualize the binary image, so you can see missing parts there !

have a look at morphological ops

also, please do us a favour, and don’t duplicate your questions ,
it means double work for anyone else here !

thanks my issue has been fixed.