Tuesday, August 15, 2017

Python: Opencv: findcontours examples

The problem with Python and Opencv is that things have been changing. 
There are many different ways to do things.
Code examples depend on installation configurations.
Code is not factored.
Numbers are used instead of constants.
Variables are reused instead of using descriptive names.

Here is the installation that was used to run this code.

https://programmingmatrix.blogspot.com/2017/08/ubuntu-conda-install-opencv-setup-and.html

Here are the posts that the code in this post is based on.

https://opencvpython.blogspot.ca/2012/06/hi-this-article-is-tutorial-which-try.html

http://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begin.html#gsc.tab=0

# This example is out of date. Use Opencv3

https://stackoverflow.com/questions/19839215/minimum-bounding-box-for-image-regions

# Now lets find the bounding boxes

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html#b-rotated-rectangle

import numpy as np
import cv2
import sys

def show_image(msg, img):
    cv2.imshow(msg, img)
    cv2.waitKey()
    cv2.destroyAllWindows()

def auto_canny(image, sigma=0.33):
    # compute the median of the single channel pixel intensities
    v = np.median(image)

    # apply automatic Canny edge detection using the computed median
    lower = int(max(0, (1.0 - sigma) * v))
    upper = int(min(255, (1.0 + sigma) * v))
    edged = cv2.Canny(image, lower, upper)

    # return the edged image
    return edged

def get_image(file_name):
    img = cv2.imread(file_name)
    show_image('original image', img)
    return img

def cvt_image_to_grayscale(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    show_image('gray scale image', img_gray)
    return img_gray

def threshold_image(img):
    ret, img_thresh = cv2.threshold(img, 127, 255, 0)
    show_image('threshold image', img_thresh)
    return img_thresh

def get_image_contours(img):
    img_contours, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    return img_contours, contours, hierarchy

def draw_image_contours(img, contours):
    img_t = cv2.drawContours(img, contours, -1, (0,255,0), 3)
    show_image('contours image', img_t)

   
###############################
   
img = get_image(sys.argv[1])
  
img_gray = cvt_image_to_grayscale(img)

img_thresh = threshold_image(img_gray)

img_contours, contours, hierarchy = get_image_contours(img_thresh)

draw_image_contours(img_gray, contours)

img_auto_canny = auto_canny(img_gray)

show_image('auto_canny image', img_auto_canny)

img_contours, contours, hierarchy = get_image_contours(img_auto_canny)

draw_image_contours(img_gray, contours)



No comments:

Post a Comment