Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2015
163
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import cv2
  2. import numpy as np
  3.  
  4. def distanceBtwPoints(p0, p1):
  5.     return np.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
  6.  
  7. def findNearestPointIndex(pt, Points):
  8.     mindistance = 1e9
  9.  
  10.     for i in range(len(Points)):
  11.         if distance < mindistance :
  12.             mindistance =  distance
  13.             nearestpointindex = i
  14.  
  15.  
  16.  
  17.     return  nearestpointindex
  18.  
  19.  
  20. if __name__ == '__main__':
  21.     img = cv2.imread("bridgeTestSource.png")
  22.     src = cv2.imread("bridgeTestSource.png")
  23.  
  24.     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  25.     gray = np.asarray(gray < 127, dtype=np.uint8) # need to cast back to uint8
  26.  
  27.  
  28.     contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  29.  
  30.     cv2.drawContours(img, contours,-1, (0,0,255), 2)
  31.  
  32.  
  33.  
  34.     cnt = contours[0]
  35.  
  36. #     for c in contours:
  37. #         if cv2.contourArea(cnt) < cv2.contourArea(c):
  38. #             cnt = c
  39. #            
  40. #     print cnt.shape
  41.     for i in range(len(contours)):
  42.         if len(cnt) < len(contours[i]):
  43.             cnt = contours[i]
  44. #     print cnt
  45.  
  46.     for i in range(len(contours)):
  47.  
  48.         if not np.array_equal(cnt, contours[i]) and len(contours[i]) > 4:
  49.             for j in range(len(contours[i])):
  50.                 pt0 = contours[i][j]
  51.  
  52.                 cnt_nearIdx = cnt[findNearestPointIndex(pt0.squeeze(), cnt.squeeze())].squeeze()
  53.                 lcnt_nearIdx = cnt_nearIdx.tolist()
  54.                 lpt0 = (pt0.squeeze()).tolist()
  55.                 tcnt_nearIdx = tuple(lcnt_nearIdx)
  56.                 tpt0 = tuple(lpt0)
  57.                
  58.                 cv2.line(img,tpt0, tcnt_nearIdx,(0,0,0),1,8)
  59.    
  60.  
  61.     cv2.imwrite('nimg.jpg', img)
  62.  
  63.     gray_src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
  64.     gray_src = np.asarray(gray_src < 127, dtype=np.uint8) # need to cast back to uint8
  65.  
  66.  
  67.     contours1, hierarchy = cv2.findContours(gray_src, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  68.  
  69.     cv2.drawContours(src, contours1,-1, (0,0,0), 0)
  70.  
  71.     m_xor= np.ones(src.shape[:2], dtype="uint8") * 255
  72.  
  73.  
  74.     ncnt = cnt.astype(np.int32)
  75.    
  76.     cv2.polylines(m_xor, [ncnt], 1, (0,0,0))
  77.    
  78.     m_xor = cv2.bitwise_xor(gray_src, m_xor, mask=m_xor)
  79.  
  80.  
  81.    
  82.     cv2.imwrite('result.jpg', m_xor)
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement