Ask Your Question

Revision history [back]

import numpy as np

import cv2

white_img = np.ones((190, 640, 3), np.uint8) * 255

(rows, cols, channels) = white_img.shape

gray = cv2.cvtColor(white_img, cv2.COLOR_BGR2GRAY)

cv2.rectangle(gray, (320, 100), (380, 190), (0, 0, 0), cv2.FILLED)
edges = cv2.Canny(gray,100,200)
cv2.imshow('gray', edges)
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

print(len(contours))

for c in contours:

    x, y, w, h = cv2.boundingRect(c)

    cv2.rectangle(white_img, (x, y), (x + w, y + h), (0, 0, 255), -1)
    cv2.rectangle(white_img, (0, 0), (x, y + h), (0, 255, 0), -1)
    cv2.rectangle(white_img, (x, 0), ( x+ w, y), (255, 0, 0), -1)
    cv2.rectangle(white_img, (white_img.shape[1] - x + w, 0), (white_img.shape[1], white_img.shape[0]), (255, 255, 0), -1)
cv2.imshow('white_img', white_img)

cv2.waitKey(0)