Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. from numpy import median
  2. from skimage.morphology import square
  3. from matplotlib import pyplot as plt
  4. import cv2
  5.  
  6. corePath = "/home/piotr/PycharmProjects/Images/samolot"
  7. fileExtension = ".jpg"
  8. images = list()
  9. colors = [(0, 255, 0), (0, 0, 255), (255, 0, 0), (0, 255, 255), (255, 0, 255), (255, 255, 0), (0, 128, 255), (255, 0, 128)]
  10.  
  11. numberOfColors = len(colors)
  12. smallAreaLimit = 3000
  13. radius = 10
  14.  
  15. def determineFileNames():
  16. for i in range(0, 10):
  17. if i == 6: continue
  18. images.append(corePath + '0' + str(i) + fileExtension)
  19.  
  20. for i in range(10, 19):
  21. images.append(corePath + str(i) + fileExtension)
  22.  
  23. def determineContours(fileName):
  24.  
  25. image = cv2.imread(fileName, cv2.IMREAD_GRAYSCALE)
  26.  
  27. med = median(image)
  28. image = cv2.erode(image, square(2), iterations=1)
  29.  
  30. sigma = 0.6
  31. lower = int(max(0, (1.0 - sigma) * med))
  32. upper = int(min(255, (1.0 + sigma) * med))
  33. image = cv2.Canny(image, lower, upper)
  34.  
  35. image = cv2.dilate(image, square(3), iterations=1)
  36. image = cv2.dilate(image, square(2), iterations=2)
  37.  
  38. _, contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  39.  
  40. return contours, hierarchy
  41.  
  42. def drawAirplaneContours(fileName, contours, hierarchy):
  43. image = cv2.imread(fileName, cv2.IMREAD_COLOR)
  44.  
  45. for i in range(0, len(contours)):
  46. if cv2.contourArea(contours[i]) > smallAreaLimit and hierarchy[0][i][3] == -1:
  47. moments = cv2.moments(contours[i])
  48. cx, cy = int(moments['m10'] / moments['m00']), int(moments['m01'] / moments['m00'])
  49. cv2.circle(image, (cx, cy), radius, (255, 255, 255), thickness=3)
  50.  
  51. cv2.drawContours(image, [contours[i]], 0, colors[i % numberOfColors], 2)
  52.  
  53. return image
  54.  
  55. def main():
  56. determineFileNames()
  57.  
  58. for picturePath in images:
  59. contours, hierarchy = determineContours(picturePath)
  60. image = drawAirplaneContours(picturePath, contours, hierarchy)
  61.  
  62. cv2.imwrite(corePath + "Contours" + picturePath[-6:], image)
  63.  
  64. if __name__ == '__main__':
  65. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement