Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- import imutils
- import operator # я его зачемто импортил но сейчас в коде не нашёл
- class ShapeDetector: # определяет форму взял со stackoverflow или какого-то друго
- def __init__(self):
- pass
- def detect(self, c):
- # initialize the shape name and approximate the contour
- shape = "unidentified"
- peri = cv2.arcLength(c, True)
- approx = cv2.approxPolyDP(c, 0.02 * peri, True)
- # if the shape is a triangle, it will have 3 vertices
- if len(approx) == 3:
- shape = "triangle"
- # if the shape has 4 vertices, it is either a square or
- # a rectangle
- elif len(approx) == 4:
- # compute the bounding box of the contour and use the
- # bounding box to compute the aspect ratio
- (x, y, w, h) = cv2.boundingRect(approx)
- ar = w / float(h)
- # a square will have an aspect ratio that is approximately
- # equal to one, otherwise, the shape is a rectangle
- shape = "square"
- # if the shape is a pentagon, it will have 5 vertices
- # otherwise, we assume the shape is a circle
- else:
- shape = "circle"
- # return the name of the shape
- return shape
- def gtc(t,image): # делает вырезку картинки объекта из оригинального изображения, чтобы его можно было классифицировать как круг, квадрат или треугольник
- x0 = int(t[1])
- y0 = int(t[0])
- return image[x0-80:x0+80,y0-80:y0+80]
- mean = lambda x: np.mean(x,0,dtype='int')[0] # функция возвращает среднее значение координат по всем пикселям
- finder =lambda n: n//200# первая координата - y, вторая - x (????) # функция ищет по координатам пикселя(20000х20000) координаты в поле 100 на 100
- def find_cters(mns): #ищет координаты
- coords = []
- for i in mns:
- a,b = i
- y = finder(a)
- x = finder(b)
- coords.append([x,y])
- return coords
- def prepc(c1): # обработка изображения именно для классификации формы
- c1 = cv2.cvtColor(c1, cv2.COLOR_BGR2GRAY)
- c1 = cv2.erode(c1,(3,3))
- c1 = cv2.blur(c1,(3,3))
- c1 = cv2.threshold(c1,90,255,cv2.THRESH_BINARY)
- return cv2.convertScaleAbs(c1[1])
- sp = ShapeDetector()
- figure_ID = {'triangle':2,'circle':1,'square':0}
- def cter(image): # финальная функция. на вход - картинку, на выходе - список объектов их типов и координат
- img = image.copy()
- ### поиск объектов на фото
- k = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
- k = cv2.erode(k,(3,3))
- k = cv2.GaussianBlur(k,(21,21),10)
- k = cv2.threshold(k,100,255,cv2.THRESH_BINARY)[1]
- cnts = cv2.findContours(k.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
- cnts = imutils.grab_contours(cnts)
- ###
- means = [mean(l) for l in cnts]
- coords = find_cters(means)
- croped = [gtc(i,image) for i in means] #смешная нарезка детей (фотографии вырезнных объектов по 1 на фото)
- answer = []
- for i in range(len(croped)):
- cnts = imutils.grab_contours(cv2.findContours(prepc(croped[i]).copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE))#поиск объектов на маленькой фоточке (обрезанной, где только 1 объект)
- cnt = cnts[np.argmax([len(x) for x in cnts])] #берём самый большой объект
- figure = sp.detect(cnt) #классификация по форме
- answer.append((figure_ID[figure],*coords[i]))
- return answer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement