Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, sys, glob
- import cv2
- import imutils
- import numpy as np
- def get_pattern(image, contours_array):
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- mask = np.zeros_like(gray)
- best_contour = sorted(contours_array, key=cv2.contourArea, reverse=True)[0]
- cv2.fillConvexPoly(mask, best_contour, 255)
- patt = np.zeros_like(image)
- patt[mask == 255] = image[mask == 255]
- (y, x) = np.where(mask == 255)
- (y_min, x_min) = (np.min(y), np.min(x))
- (y_max, x_max) = (np.max(y), np.max(x))
- pattern = patt[y_min:y_max + 1, x_min:x_max + 1]
- h,w,_ = pattern.shape
- if h > w:
- patt = imutils.rotate_bound(patt, 90)
- print(h,w)
- return patt
- path = input("Path to folder: ")
- #path = "C:/Users/jesch/Desktop/test"
- if path.__len__() == 0:
- path = os.path.dirname(os.path.abspath(__file__))
- dirs = os.listdir(path)
- backSub = cv2.createBackgroundSubtractorMOG2()
- for item in dirs:
- if item.endswith('.jpg') or item.endswith('.JPEG') or item.endswith('.jpeg') or item.endswith('.png') or item.endswith('.bmp'):
- image = cv2.imread(path +'/'+ item)
- image_gray = cv2.imread(path +'/'+ item,0)
- kernel = np.ones((1, 1), np.uint8)
- image_gray = cv2.morphologyEx(image_gray, cv2.MORPH_CLOSE, kernel)
- smoothed = cv2.bilateralFilter(image_gray, 7, 50, 50)
- canny = cv2.Canny(smoothed, 10, 20)
- contour, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- cropped = get_pattern(image, contour)
- hi,wi,_ = cropped.shape
- if hi > wi:
- if hi > 800:
- cropped = imutils.resize(cropped, height= 800)
- else:
- if wi > 1800:
- cropped = imutils.resize(cropped, height= 1800)
- #cv2.drawContours(image, contour, -1, (0, 255, 0), -1)
- '''cv2.imshow('image', image)
- cv2.imshow('image3', canny)'''
- #cv2.namedWindow("image4", cv2.WINDOW_NORMAL)
- cv2.imshow('image4', cropped)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement