Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.00 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import imutils
  4. import operator # я его зачемто импортил но сейчас в коде не нашёл
  5.  
  6.  
  7. class ShapeDetector: # определяет форму взял со stackoverflow или какого-то друго
  8.     def __init__(self):
  9.         pass
  10.  
  11.     def detect(self, c):
  12.         # initialize the shape name and approximate the contour
  13.         shape = "unidentified"
  14.         peri = cv2.arcLength(c, True)
  15.         approx = cv2.approxPolyDP(c, 0.02 * peri, True)
  16.  
  17. # if the shape is a triangle, it will have 3 vertices
  18.         if len(approx) == 3:
  19.             shape = "triangle"
  20.  
  21.         # if the shape has 4 vertices, it is either a square or
  22.         # a rectangle
  23.         elif len(approx) == 4:
  24.             # compute the bounding box of the contour and use the
  25.             # bounding box to compute the aspect ratio
  26.             (x, y, w, h) = cv2.boundingRect(approx)
  27.             ar = w / float(h)
  28.  
  29.             # a square will have an aspect ratio that is approximately
  30.             # equal to one, otherwise, the shape is a rectangle
  31.             shape = "square"
  32.  
  33.         # if the shape is a pentagon, it will have 5 vertices
  34.         # otherwise, we assume the shape is a circle
  35.         else:
  36.             shape = "circle"
  37.  
  38.         # return the name of the shape
  39.         return shape
  40.    
  41. def gtc(t,image): # делает вырезку картинки объекта из оригинального изображения, чтобы его можно было классифицировать как круг, квадрат или треугольник
  42.     x0 = int(t[1])
  43.     y0 = int(t[0])
  44.     return image[x0-80:x0+80,y0-80:y0+80]
  45.  
  46. mean = lambda x: np.mean(x,0,dtype='int')[0] # функция возвращает среднее значение координат по всем пикселям
  47.  
  48. finder =lambda n: n//200# первая координата - y, вторая - x (????) # функция ищет по координатам пикселя(20000х20000) координаты в поле 100 на 100
  49.  
  50. def find_cters(mns): #ищет координаты  
  51.     coords = []
  52.     for i in mns:
  53.         a,b = i
  54.         y = finder(a)
  55.         x = finder(b)
  56.         coords.append([x,y])
  57.     return coords
  58.  
  59. def prepc(c1):  # обработка изображения именно для классификации формы
  60.     c1 = cv2.cvtColor(c1, cv2.COLOR_BGR2GRAY)
  61.     c1 = cv2.erode(c1,(3,3))
  62.     c1 = cv2.blur(c1,(3,3))
  63.     c1 = cv2.threshold(c1,90,255,cv2.THRESH_BINARY)
  64.     return cv2.convertScaleAbs(c1[1])
  65.  
  66. sp = ShapeDetector()
  67.  
  68. figure_ID = {'triangle':2,'circle':1,'square':0}
  69.  
  70. def cter(image): # финальная функция. на вход - картинку, на выходе - список объектов их типов и координат
  71.     img = image.copy()
  72.    
  73.     ### поиск объектов на фото
  74.     k = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  75.     k = cv2.erode(k,(3,3))
  76.     k = cv2.GaussianBlur(k,(21,21),10)
  77.     k = cv2.threshold(k,100,255,cv2.THRESH_BINARY)[1]
  78.     cnts = cv2.findContours(k.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
  79.     cnts = imutils.grab_contours(cnts)
  80.     ###
  81.  
  82.     means = [mean(l) for l in cnts]
  83.    
  84.     coords = find_cters(means)
  85.     croped = [gtc(i,image) for i in means] #смешная нарезка детей (фотографии вырезнных объектов по 1 на фото)
  86.    
  87.     answer = []
  88.     for i in range(len(croped)):
  89.         cnts = imutils.grab_contours(cv2.findContours(prepc(croped[i]).copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE))#поиск объектов на маленькой фоточке (обрезанной, где только 1 объект)
  90.         cnt = cnts[np.argmax([len(x) for x in cnts])] #берём самый большой объект
  91.         figure = sp.detect(cnt) #классификация по форме
  92.         answer.append((figure_ID[figure],*coords[i]))
  93.     return answer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement