Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Code:

#!/usr/bin/env python37
#Raspberry pi 3/4, OpenCV 4.1.2
#Date: November 18th 2019

import cv2 as cv
import numpy as np

def select_blue(image):
    hsv = cv.cvtColor(image, cv.COLOR_RGB2HSV)
    # blue color mask
    lower = np.uint8([100,50,50])
    upper = np.uint8([130,255,255])
    blue_mask = cv.inRange(image, lower, upper)

    return blue_mask # cv.bitwise_and(image, image, mask = mask)

while True:
    frame = cv.imread('map.png')
    hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)

    mask =  select_blue(hsv)

    element = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
    mask = cv.erode(mask,element, iterations=2)
    mask = cv.dilate(mask,element,iterations=2)
    mask = cv.erode(mask,element)

    contours, hierarchy = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    maximumArea = 0
    bestContour = None
    for contour in contours:
        currentArea = cv.contourArea(contour)
        if currentArea > maximumArea:
            bestContour = contour
            maximumArea = currentArea
    if bestContour is not None:
        x,y,w,h = cv.boundingRect(bestContour)
        cv.rectangle(frame, (x,y),(x+w,y+h), (0,0,255), 1)        

    cv.imwrite('map.jpg', frame)    
    cv.imshow('frame',frame)

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cv.destroyAllWindows()

Output: detect_map