Ask Your Question

Revision history [back]

see my trial code

#!/usr/bin/env python

# Python 2/3 compatibility
from __future__ import print_function

import numpy as np
import cv2 as cv

# built-in modules
import os
import sys

def main():
    try:
        src = sys.argv[1]
    except:
        src = "C:/build/opencv4.0.1/bin/Release/15546357708304171.jpg"

    frame = cv.imread(src)
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

    bin = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 3, 9)
    bin = cv.medianBlur(bin, 3)
    bin = cv.medianBlur(bin, 3)
    dilate = cv.dilate(bin, None, iterations=2)
    bin = cv.GaussianBlur(bin, (45,45),0)
    ret, bin = cv.threshold(bin, 0,255, cv.THRESH_BINARY)       
    contours, heirs = cv.findContours( bin, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)

    largest_contour=0
    for idx, contour in enumerate(contours):

        area=cv.contourArea(contour)
        if (area >largest_contour) :
            largest_contour=area           
            largest_index=idx

    r = cv.boundingRect(contours[largest_index])
    cv.rectangle(frame,r,(0,0,255),3)
    cv.imshow('frame', frame)
    cv.imshow('dilate', dilate)

    cv.imshow('bin', bin)
    cv.waitKey()


if __name__ == '__main__':
    main()
    cv.destroyAllWindows()

see my trial code that inspired by this sample and this post

#!/usr/bin/env python

# Python 2/3 compatibility
from __future__ import print_function

import numpy as np
import cv2 as cv

# built-in modules
import os
import sys

def main():
    try:
        src = sys.argv[1]
    except:
        src = "C:/build/opencv4.0.1/bin/Release/15546357708304171.jpg"

    frame = cv.imread(src)
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

    bin = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 3, 9)
    bin = cv.medianBlur(bin, 3)
    bin = cv.medianBlur(bin, 3)
    dilate = cv.dilate(bin, None, iterations=2)
    bin = cv.GaussianBlur(bin, (45,45),0)
    ret, bin = cv.threshold(bin, 0,255, cv.THRESH_BINARY)       
    contours, heirs = cv.findContours( bin, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)

    largest_contour=0
    for idx, contour in enumerate(contours):

        area=cv.contourArea(contour)
        if (area >largest_contour) :
            largest_contour=area           
            largest_index=idx

    r = cv.boundingRect(contours[largest_index])
    cv.rectangle(frame,r,(0,0,255),3)
    cv.imshow('frame', frame)
    cv.imshow('dilate', dilate)

    cv.imshow('bin', bin)
    cv.waitKey()


if __name__ == '__main__':
    main()
    cv.destroyAllWindows()