Advertisement
Guest User

lab_1 (background) WNO

a guest
Feb 24th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. import os, sys, glob
  2. import cv2
  3. import imutils
  4. import numpy as np
  5.  
  6. def get_pattern(image, contours_array):
  7.  
  8.     gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  9.     mask = np.zeros_like(gray)
  10.  
  11.     best_contour = sorted(contours_array, key=cv2.contourArea, reverse=True)[0]
  12.     cv2.fillConvexPoly(mask, best_contour, 255)
  13.  
  14.     patt = np.zeros_like(image)
  15.     patt[mask == 255] = image[mask == 255]
  16.  
  17.     (y, x) = np.where(mask == 255)
  18.     (y_min, x_min) = (np.min(y), np.min(x))
  19.     (y_max, x_max) = (np.max(y), np.max(x))
  20.     pattern = patt[y_min:y_max + 1, x_min:x_max + 1]
  21.     h,w,_ = pattern.shape
  22.     if h > w:
  23.         patt = imutils.rotate_bound(patt, 90)
  24.     print(h,w)
  25.     return patt
  26.  
  27. path = input("Path to folder: ")
  28. #path = "C:/Users/jesch/Desktop/test"
  29.  
  30. if path.__len__() == 0:
  31.     path = os.path.dirname(os.path.abspath(__file__))
  32.  
  33. dirs = os.listdir(path)
  34.  
  35. backSub = cv2.createBackgroundSubtractorMOG2()
  36.  
  37. for item in dirs:
  38.     if item.endswith('.jpg') or item.endswith('.JPEG') or item.endswith('.jpeg') or item.endswith('.png') or item.endswith('.bmp'):
  39.  
  40.         image = cv2.imread(path +'/'+ item)
  41.         image_gray = cv2.imread(path +'/'+ item,0)
  42.  
  43.         kernel = np.ones((1, 1), np.uint8)
  44.         image_gray = cv2.morphologyEx(image_gray, cv2.MORPH_CLOSE, kernel)
  45.  
  46.         smoothed = cv2.bilateralFilter(image_gray, 7, 50, 50)
  47.         canny = cv2.Canny(smoothed, 10, 20)
  48.  
  49.         contour, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  50.  
  51.         cropped = get_pattern(image, contour)
  52.  
  53.         hi,wi,_ = cropped.shape
  54.  
  55.         if hi > wi:
  56.             if hi > 800:
  57.                 cropped = imutils.resize(cropped, height= 800)
  58.         else:
  59.             if wi > 1800:
  60.                 cropped = imutils.resize(cropped, height= 1800)
  61.  
  62.  
  63.         #cv2.drawContours(image, contour, -1, (0, 255, 0), -1)
  64.  
  65.         '''cv2.imshow('image', image)
  66.        cv2.imshow('image3', canny)'''
  67.         #cv2.namedWindow("image4", cv2.WINDOW_NORMAL)
  68.         cv2.imshow('image4', cropped)
  69.         cv2.waitKey(0)
  70.         cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement