-
-
Save OlegJakushkin/1f89548434905a281c770d9af8af1eb6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
from os.path import basename | |
import cv2 | |
import numpy | |
import numpy as np | |
path = "/headless/shared/output.png" | |
if(len(sys.argv) >= 2): | |
path = sys.argv[1] | |
img = cv2.imread(path) | |
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
_, img_bin = cv2.threshold(img_gray, 0, 255, | |
cv2.THRESH_OTSU) | |
img_bin = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, | |
numpy.ones((3, 3), dtype=int)) | |
border = img_bin.copy() | |
border = cv2.erode(border, None) | |
border = cv2.erode(border, None) | |
ret, thresh = cv2.threshold(border, 127, 255, 0) | |
image, contours, hierarchy = cv2.findContours(thresh, 1, 2) | |
cnt = contours[0] | |
M = cv2.moments(cnt) | |
img_rgb = cv2.cvtColor(img_bin, cv2.COLOR_GRAY2BGR) | |
cv2.drawContours(img_rgb, contours, -1, (0, 0, 255), 2) | |
cv2.imwrite("dbg."+basename(path)+".png", img_rgb) | |
big_height, big_width = img_bin.shape | |
for i, cnt in enumerate(contours): | |
x, y, width, height = cv2.boundingRect(cnt) | |
if width < 20 or height < 20: | |
continue; | |
im_clone = np.zeros((big_width, big_height, 3), np.uint8) | |
im_clone[:] = (255, 255, 255) | |
cv2.drawContours(im_clone, contours, i, (0, 0, 0), 2) | |
roi = im_clone[x:x + width, y:y + height] | |
name = './roi.'+basename(path) +'.'+str(i)+'.png' | |
cv2.imwrite(name, im_clone[y:y + height, x:x + width]) | |
if os.path.getsize(name) <=0: | |
os.remove(name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment