Home > Software engineering >  How should I properly extract the digital from 7 segment display in python
How should I properly extract the digital from 7 segment display in python

Time:12-29

I am working on a project about extracting the digit from the 7-segment display and I am following this guide: original photo

The extracted black white photo:

black white photo

Code:


    img_name = 'test2.jpeg'
    image = cv2.imread(img_name)

    image = imutils.resize(image, height=1000)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edged = cv2.Canny(blurred, 50, 200, 255)


    #cv2.imshow("test", edged)
    #cv2.waitKey(0)

    cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)

    displayCnt = None
    # loop over the contours
    for c in cnts:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)
        # if the contour has four vertices, then we have found
        # the thermostat display
        if len(approx) == 4:
            displayCnt = approx
            break
    warped = four_point_transform(gray, displayCnt.reshape(4, 2))
    output = four_point_transform(image, displayCnt.reshape(4, 2))

    thresh = cv2.threshold(warped, 222, 255, cv2.THRESH_BINARY_INV cv2.THRESH_OTSU)[1]
    cv2.imwrite("black.png", thresh)

CodePudding user response:

Regarding the brightness difference, division normalization and sharping can be applied:

smooth = cv2.GaussianBlur(warped, (95,95), 0)
division = cv2.divide(warped, smooth, scale=255)
sharp = filters.unsharp_mask(division, radius=1.5, amount=1.5, 
        multichannel=False, preserve_range=False)
sharp = (255*sharp).clip(0,255).astype(np.uint8)

Output:

enter image description here

CodePudding user response:

Due to different parts of the image having different overall brightness levels, a global threshold will result in some parts of the image having a threshold that's too low and some too high. This can be remedied by using a median filter on the image to determine local thresholds for the entire image. Here are the steps described (and demonstrated using Paint.NET).

  1. Apply a median filter to the image

Median filter

  1. Take the difference between the original image and the filtered image and convert it to grayscale

Difference between the original and blurred image (grayscale)

  1. Use a global threshold on this new image

Threshold

  • Related