Advertisement
kfirbarzilay

mask

Apr 21st, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.94 KB | None | 0 0
  1. # import the necessary packages
  2. from tkinter import W
  3.  
  4. import cv2
  5. import os, os.path
  6. import numpy as np
  7.  
  8. # debug info OpenCV version
  9. print("OpenCV version: " + cv2.__version__)
  10.  
  11. # image path and valid extensions
  12. imageDir = "/home/eden/data/VOCdevkit/VOC2007/JPEGImages"  # specify your path here
  13. image_path_list = []
  14. valid_image_extensions = [".jpg", ".jpeg", ".png", ".tif", ".tiff"]  # specify your valid extensions here
  15. valid_image_extensions = [item.lower() for item in valid_image_extensions]  # sorting endings
  16.  
  17. # create a list of all the images in directory and
  18. # append images with a vaild extention to image_path_list
  19. for file in os.listdir(imageDir):
  20.     extension = os.path.splitext(file)[1]
  21.     if extension.lower() not in valid_image_extensions:
  22.         continue
  23.     image_path_list.append(os.path.join(imageDir, file))
  24. image_path_list = sorted(image_path_list)
  25.  
  26. # loop through image_path_list to open each image
  27. for imagePath in image_path_list:
  28.     image = cv2.imread(imagePath)
  29.     # resize the image blur it and convert it to HSV color space
  30.     # image =imutils.resize(image, width=500, height=375)
  31.     blurred = cv2.GaussianBlur(image, (5, 5), 0)
  32.     hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
  33.  
  34.     # define the lower and upper boundaries in the HSV coordiantes.
  35.     lower = np.array([90, 85, 0])
  36.     upper = np.array([120, 255, 255])
  37.  
  38.     # define a filtering kernel
  39.     kernel = np.ones((5, 5), np.uint8)
  40.  
  41.     # construct a mask for the desired color range, then perform a series of
  42.     # erosions and dilations (or opening and closing) to remove any small noise left
  43.     mask = cv2.inRange(hsv, lower, upper)
  44.     mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)  # opening
  45.     mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)  # closing
  46.     res = cv2.bitwise_and(image, image, mask=mask)
  47.  
  48.     # find contours in the mask and initialize the current
  49.     # (x, y) center of the objects
  50.     cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
  51.                             cv2.CHAIN_APPROX_SIMPLE)[-2]
  52.     center = None
  53.  
  54.     # only proceed if at least one contour was found
  55.     if len(cnts) > 0:
  56.         for i in range(len(cnts)):
  57.             x, y, w, h = cv2.boundingRect(cnts[i])  # retrieves a bounding rectangle pixel locations
  58.             M = cv2.moments(cnts[i])  # the contour moments
  59.             center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))  # x and Y center of mass
  60.             # only proceed if the rectangle meets a minimum size
  61.             # only look in the bottom third part of the image, overlook the car
  62.             if 250 < center[1] < 350:
  63.                 print(w,h)
  64.                 if 20 < w < 50 and 20 < h < 40:
  65.                     # draw the box and centroid on the image
  66.                     cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
  67.                        #annotate the bounding box to a new file
  68.                     up_x = x
  69.                     up_y = y
  70.                     down_x = x + w
  71.                     down_y = y + h
  72.                     with open(imagePath +".txt","a+")  as dataFile:
  73.                         dataFile.write(" ".join([" cone",str(up_x),str(up_y),str(down_x),str(down_y)]))
  74. #
  75.     # #show the resulted image (and optionally mask and res)
  76.     # cv2.imshow('image', image)
  77.     # #     # cv2.imshow('mask',mask)
  78.     # #     # cv2.imshow('res',res)
  79.     # # #    #0 = wait indefinitely
  80.     # # #    #exit when escape key is pressed
  81.     # key = cv2.waitKey(0)
  82.     # if key == 27:  # escape
  83.     #     break
  84.     # #
  85.     # #    # close any open windows
  86.     # cv2.destroyAllWindows()
  87. #
  88. # xml_files = []
  89. # #get the text files
  90. # def get_txt_files(path):
  91. #     for file in os.listdir(path):
  92. #         extension = os.path.splitext(file)[1]
  93. #         if extension == ".txt":
  94. #             xml_files.append(os.path.join(path, file))
  95. #         else:
  96. #             continue
  97. #
  98. # get_txt_files
  99.  
  100. # xml_files = sorted(xml_files)
  101. # #the xml format
  102. # def create_xml(text,name):
  103. #     xmls = ['<annotation>\n', '\t<folder>VOC2007</folder>\n', '\t<filename>000026.jpg</filename>\n', '\t<source>\n', '\t\t<database>The VOC2007 Database</database>\n', '\t\t<annotation>PASCAL VOC2007</annotation>\n', '\t\t<image>flickr</image>\n', '\t\t<flickrid>192073981</flickrid>\n', '\t</source>\n', '\t<owner>\n', '\t\t<flickrid>tobeng</flickrid>\n', '\t\t<name>kfir_yotam</name>\n', '\t</owner>\n', '\t<size>\n', '\t\t<width>1280</width>\n', '\t\t<height>720</height>\n', '\t\t<depth>3</depth>\n', '\t</size>\n', '\t<segmented>0</segmented>\n', '\t<object>\n', '\t\t<name>car</name>\n', '\t\t<pose>unspecified</pose>\n', '\t\t<truncated>0</truncated>\n', '\t\t<difficult>0</difficult>\n', '\t\t<bndbox>\n', '\t\t\t<xmin>90</xmin>\n', '\t\t\t<ymin>125</ymin>\n', '\t\t\t<xmax>337</xmax>\n', '\t\t\t<ymax>212</ymax>\n', '\t\t</bndbox>\n', '\t</object>\n', '</annotation>\n']
  104. #     annotation_data = text.read()
  105. #     file_name = name
  106. #     object_name = "cone"
  107. #     x_min = annotation_data.split(' ')[2]
  108. #     y_min = annotation_data.split(' ')[3]
  109. #     x_max = annotation_data.split(' ')[4]
  110. #     y_max = annotation_data.split(' ')[5]
  111. #     xmls[2]= '\t<filename>'+file_name+'</filename>\n'
  112. #     xmls[20]= '\t\t<name>'+object_name+'</name>\n'
  113. #     xmls[25]= '\t\t\t<xmin>'+x_min+'</xmin>\n'
  114. #     xmls[26]= '\t\t\t<ymin>'+y_min+'</ymin>\n'
  115. #     xmls[27]= '\t\t\t<xmax>'+x_max+'</xmax>\n'
  116. #     xmls[28]= '\t\t\t<ymax>'+y_max+'</ymax>\n'
  117. #     return xmls
  118. #
  119. # #write a list of XML to file
  120. # def write_to_file(xmls,file_name):
  121. #     f = open(file_name,'w')
  122. #     for line in xmls:
  123. #         f.write(line)
  124. #     f.close()
  125. #
  126. # def convert(file_name, text):
  127. #     xmls = create_xml(text,name)
  128. #     write_to_file(xmls,file_name.split('.')[0]+'.xml')
  129. # #loop through .txt files and create .xml
  130. # for j in range(len(xml_files)):
  131. #     text = open(xml_files[j],'r')
  132. #     name = os.path.basename(xml_files[j])
  133. #     name = os.path.splitext(name)[0]
  134. #     convert(name, text)
  135. #
  136. #
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement