#!/bin/python #python 3.6.0 import numpy import cv2 import math import sys def thresh (img, minv, maxv) : ret, thresh = cv2.threshold(img, minv, 255, cv2.THRESH_BINARY) ret, ithresh = cv2.threshold(img, maxv, 255, cv2.THRESH_BINARY_INV) return cv2.bitwise_and(thresh,ithresh) img = cv2.imread(sys.argv[1]) #blur, kernel is the distance of pixels the rurrounding ones are #29 seems to be upper lmit on effectiveness. himg = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) h,s,v = cv2.split(himg) # i think the range for red is 0 10, 170 179 #blue is 195-135, 40? really that much? #hue only testing, not very effective. # better with saturation #red #thresh = cv2.bitwise_and(cv2.bitwise_or(thresh(h,0,10),thresh(h,169,180)), thresh(s,60,255)) #blue thresh = cv2.bitwise_and(thresh(h,95,135), thresh(s,60,255)) #thresh = cv2.GaussianBlur(thresh,(29,29),0,0,cv2.BORDER_REFLECT_101) cv2.imwrite("stallmask.jpg",thresh); mask = cv2.merge((thresh,thresh,thresh)) masked = cv2.bitwise_and(himg, mask); cv2.imwrite("stallmasked.jpg",cv2.cvtColor(masked,cv2.COLOR_HSV2BGR)); #only takes 1 cannel arrays? im2, con, heir = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #number of contours above certain size vc = 0 for i in range(0, len(con)) : if (cv2.contourArea(con[i]) > 2000) : a = cv2.contourArea(con[i]) cv2.drawContours(masked, con, i, (120,255,255), 5) (cx, cy), r = cv2.minEnclosingCircle(con[i]) p = 1- ( a / (math.pi * math.pow(r, 2))) c = (int(cx),int(cy)) cv2.circle(masked, c,int(r), (150,255,255), 5) if (p < .35) : print("yee") conmask = numpy.zeros(v.shape, numpy.uint8) cv2.drawContours(conmask, con, i, (255), cv2.FILLED) conmasked = cv2.bitwise_and(v, conmask) meanconmasked = conmasked.sum().sum() / a print(meanconmasked) ret, conmasked = cv2.threshold(conmasked, meanconmasked, 255, cv2.THRESH_BINARY_INV) cv2.imwrite("conmasked" + str(i) + ".jpg",cv2.merge((conmasked,conmasked,conmasked))) im2, rcon, rheir = cv2.findContours(conmasked, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cv2.drawContours(masked, rcon, -1, (50, 255, 255),2) print(p) vc = vc + 1 else : cv2.drawContours(masked, con, i, (80,255,255), 1) cv2.imwrite("stallmaskedcon.jpg",cv2.cvtColor(masked,cv2.COLOR_HSV2BGR)) print("properly sized contours") print(vc) print("all contours") print(len(con))