Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. import sys, os
  2. import numpy as np
  3. import cv2
  4.  
  5. inpath = sys.argv[1] if sys.argv[1:] else 'tNzoqGH.jpg'
  6. im = cv2.imread(inpath)
  7. h,w = im.shape[:2]
  8.  
  9. # where's the map?
  10. if 1:
  11.     grayim = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
  12.     mask = (grayim <= 254) * np.uint8(255)
  13.  
  14.     kernel = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(9,9))
  15.  
  16.     mask = cv2.morphologyEx(src=mask, op=cv2.MORPH_CLOSE, kernel=kernel, iterations=1)
  17.     mask = cv2.morphologyEx(src=mask, op=cv2.MORPH_OPEN, kernel=kernel, iterations=4)
  18.  
  19.     contourimg, contours, hierarchy = \
  20.         cv2.findContours(image=mask, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_TC89_KCOS)
  21.  
  22.     rectangles = []
  23.     for c in contours:
  24.         peri = cv2.arcLength(c, True)
  25.         approx = cv2.approxPolyDP(c, 0.04*peri, True)
  26.         if len(approx) == 4:
  27.             rectangles.append(approx)
  28.  
  29.     rectangles.sort(key=lambda c: cv2.contourArea(c))
  30.     #print [cv2.arcLength(c, True) for c in rectangles]
  31.     largestrect = rectangles[-1]
  32.     print largestrect[:,0] # eh...
  33.  
  34.     outim = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
  35.  
  36.     cv2.drawContours(outim, [largestrect], -1, (0, 0, 255), 5)
  37.  
  38.     cv2.imwrite(os.path.splitext(inpath)[0] + "-mask.png", outim)
  39.  
  40.  
  41.  
  42. if 0:
  43.     K = 4
  44.  
  45.     im = cv2.cvtColor(im, cv2.COLOR_BGR2YUV)
  46.  
  47.     pixels = im.reshape((-1, 3)).astype(np.float32)
  48.     pixels = pixels[:,1:3]
  49.  
  50.     crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 10, 0.1)
  51.     rv, labels, centers = cv2.kmeans(pixels, K=K, bestLabels=None, criteria=crit, attempts=1, flags=0)
  52.  
  53.     labelcols = np.hstack([ [[0]]*K, centers ])
  54.     labelcols[:,0] = 128
  55.     labelcols[labels[0][0]] = (0, 128, 128)
  56.  
  57.  
  58.     out = labelcols[labels[:,0]]
  59.     out = out.reshape((h,w,3)).clip(0, 255).astype(np.uint8)
  60.     #out[:,:,0] = im[:,:,0]
  61.     out = cv2.cvtColor(out, cv2.COLOR_YUV2BGR)
  62.  
  63.     cv2.imwrite(os.path.splitext(inpath)[0] + "-clustered.png", out)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement