Example #1
0
def img_callback(data):
	try:
		image = br.imgmsg_to_cv2(data,"bgr8")
		segm = cnt.segmentacao(image)
		cv2.imshow("seg",segm)
		cx,cy,seg = cnt.centroid(segm,image)
		cx = np.asarray(cx)
		cy = np.asarray(cy)
		_cx = 0
		_cy = 0
		if not cx is None and not cy is None:
			for k in range(len(cx)):
				_cx = (_cx+cx[k])/(k+1)
				_cy = (_cy+cy[k])/(k+1)
				cv2.circle(seg, (int(cx[k]), int(cy[k])), 7, (0,255,0), -1)
		cv2.circle(seg, (int(_cx), int(_cy)), 7, (0,255,0), -1)		
		print _cy,_cx
		'''
		if not cx is None and not cy is None:
			for k in range(cx):
				cv2.circle(image, (int(cx[k]), int(cy[k])), 7, (0,255,0), -1)
		'''
		cv2.imshow("frame",seg)
		cv2.waitKey(1)
	except CvBridgeError, e:
		print e
Example #2
0
def square_3(length, side):
    p1 = POLYGON.pos()
    POLYGON.backward(side)
    p2 = POLYGON.pos()
    POLYGON.left(90)
    POLYGON.forward(length)
    p3 = POLYGON.pos()
    POLYGON.right(90)
    POLYGON.forward(side)
    p4 = POLYGON.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)
    sq = {'centro': centro, 'p1': p1, 'p2': p2, 'p3': p3, 'p4': p4}
    return sq
Example #3
0
def square_3(LENGTH, SIDE):
    """To draw square type 3"""
    p1 = POLYGON.pos()
    POLYGON.backward(SIDE)
    p2 = POLYGON.pos()
    POLYGON.left(90)
    POLYGON.forward(LENGTH)
    p3 = POLYGON.pos()
    POLYGON.right(90)
    POLYGON.forward(SIDE)
    p4 = POLYGON.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)
    sq = {'centro': centro, 'p1': p1, 'p2': p2, 'p3': p3, 'p4': p4}
    return sq
Example #4
0
def align(filelist, coords=None, rad=None, aligned=False, manual=False):
    if len(filelist) < 2:
        raise Exception('At least 2 input images required')

    if not coords:
        h = pyfits.getheader(filelist[0])
        coords = [int(h['XCEN']), int(h['YCEN'])]

    centers = []
    if not aligned:
        # Centroid on all images
        print 'Centroiding...'
        for filename in filelist:
            center = centroid(filename, coords, rad, manual=manual)
            print center
            print '%s: (%.2f,%.2f)' % (filename, center[0], center[1])
            centers.append(center)

    else:
        # Read centers
        for filename in filelist:
            h = pyfits.getheader(filename)
            centers.append([int(h['XCEN']), int(h['YCEN'])])

    # Shift to center of first image
    centers = np.array(centers)
    shifts = centers - centers[0]
    if aligned:
        shifts = [(-x[1], -x[0]) for x in shifts]
    print
    print 'ref: %s (%.2f,%.2f)' % (filelist[0], centers[0][0], centers[0][1])
    print

    newNames = []
    for filename, shift in zip(filelist, shifts):
        if aligned:
            name_ext = ''
        else:
            name_ext = '.al'
        newName = imshift(filename,
                          shift,
                          centers[0],
                          filelist[0],
                          name_ext,
                          clobber=True)
        newNames.append(newName)

    return zip(newNames, centers, shifts)
Example #5
0
def square(side, length):
    POLYGON.forward(side)
    POLYGON.right(90)
    p1 = POLYGON.pos()
    POLYGON.forward(length)
    POLYGON.right(120)
    p2 = POLYGON.pos()
    POLYGON.forward(length)
    POLYGON.right(90)
    p3 = POLYGON.pos()
    POLYGON.forward(side)
    POLYGON.right(60)
    p4 = POLYGON.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)  #being called from centroid.py
    sq = {'centro': centro, 'p1': p1, 'p2': p2, 'p3': p3, 'p4': p4}
    return sq
Example #6
0
def square(side, length):  # number of each square side
    POLYGON.forward(side)
    POLYGON.right(90)
    p1 = POLYGON.pos()
    POLYGON.forward(length)
    POLYGON.right(120)
    p2 = POLYGON.pos()
    POLYGON.forward(length)
    POLYGON.right(90)
    p3 = POLYGON.pos()
    POLYGON.forward(side)
    POLYGON.right(60)
    p4 = POLYGON.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)  #being called from centroid.py
    sq = {'centro': centro, 'p1': p1, 'p2': p2, 'p3': p3, 'p4': p4}
    #print(f'centro {centro} p1 {p1} p2 {p2} p3 {p3} p4 {p4}')
    return sq
Example #7
0
def square_3(l):
    p1 = polygon.pos()
    polygon.backward(10)
    p2 = polygon.pos()
    polygon.left(90)
    polygon.forward(l)
    p3 = polygon.pos()
    polygon.right(90)
    polygon.forward(10)
    p4 = polygon.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)
    bp1 = turtle.Turtle()
    bp1.penup()
    bp1.setpos(centro)
    bp1.color("cyan")
    print(f'centro {centro} p1 {p1} p2 {p2} p3 {p3} p4 {p4}')
    return centro
Example #8
0
def square(SIDE, LENGTH):
    """To draw square"""
    POLYGON.forward(SIDE)
    POLYGON.right(90)
    p1 = POLYGON.pos()
    POLYGON.forward(LENGTH)
    POLYGON.right(120)
    p2 = POLYGON.pos()
    POLYGON.forward(LENGTH)
    POLYGON.right(90)
    p3 = POLYGON.pos()
    POLYGON.forward(SIDE)
    POLYGON.right(60)
    p4 = POLYGON.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)  #being called from centroid.py
    sq = {'centro': centro, 'p1': p1, 'p2': p2, 'p3': p3, 'p4': p4}
    return sq
Example #9
0
def align(filelist,coords=None,rad=None,aligned=False,manual=False):
    if len(filelist) < 2:
        raise Exception('At least 2 input images required')
    
    if not coords:
        h = pyfits.getheader(filelist[0])
        coords = [int(h['XCEN']),int(h['YCEN'])]

    centers = []
    if not aligned:
        # Centroid on all images
        print 'Centroiding...'
        for filename in filelist:
            center = centroid(filename,coords,rad,manual=manual)
            print center
            print '%s: (%.2f,%.2f)' % (filename,center[0],center[1])
            centers.append(center)

    else:
        # Read centers
        for filename in filelist:
            h = pyfits.getheader(filename)
            centers.append([int(h['XCEN']),int(h['YCEN'])])
        

    # Shift to center of first image
    centers = np.array(centers)
    shifts = centers-centers[0]
    if aligned:
        shifts = [(-x[1],-x[0]) for x in shifts]
    print
    print 'ref: %s (%.2f,%.2f)' % (filelist[0],centers[0][0],centers[0][1])
    print

    newNames = []
    for filename,shift in zip(filelist,shifts):
        if aligned:
            name_ext = ''
        else:
            name_ext = '.al'
        newName = imshift(filename,shift,centers[0],filelist[0],name_ext,clobber=True)
        newNames.append(newName)

    return zip(newNames,centers,shifts)
Example #10
0
def square_3(length, side):  # Number of each square side
    p1 = POLYGON.pos()
    POLYGON.backward(side)
    p2 = POLYGON.pos()
    POLYGON.left(90)
    POLYGON.forward(length)
    p3 = POLYGON.pos()
    POLYGON.right(90)
    POLYGON.forward(side)
    p4 = POLYGON.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)
    """ bp1 = turtle.Turtle()
    bp1.penup()
    bp1.setpos(centro)
    bp1.color("cyan") """
    sq = {'centro': centro, 'p1': p1, 'p2': p2, 'p3': p3, 'p4': p4}
    #print(f'centro {centro} p1 {p1} p2 {p2} p3 {p3} p4 {p4}')
    return sq
Example #11
0
 def main_loop(self):
     """
     Single iteration of the application's main loop.
     """
     # Get current image frame from the camera
     frame = self.camera.get_frame()
     self.h,self.w,_c= frame.shape
     
     self.current_centroid = centroid(np.sum(frame,2)/3)
     
     #display unaltered frame
     #imshow("Original",frame)
     
     #collect the output frame for display
     output_frame = process_image(frame,self.current_centroid,self.centroid_1,self.centroid_2,self.centroid_1_active,self.centroid_2_active)
     
     #show the processed/annotated output frame
     imshow("Processed",output_frame)
     
     #handle any key presses
     self.key_handler()
def global_distance_factor(coords):
    center = centroid(coords)
    r = []

    n = len(coords)
    for i in range(n - 1):  # the last point in coords is a duplicate, so skip it
        r.append(distance(center, coords[i]))

    r_max = max(r)

    # normalize values in r to the interval 0 to 1
    for i in range(len(r)):
        r[i] = r[i] / r_max

    h_dist = []  # distance entropy
    e_dist = []  # quantization error

    j = 1
    while 2 ** j <= n * 2:
        k = 2 ** j
        h = histogram(k, r, max(r))
        h_dist.append(entropy(h, n - 1))
        e_dist.append(quantization_error(h, n - 1))
        j += 1

    # Although Chen & Sundarum say there's a theoretical
    # maximum constant quantization error, it isn't specified.
    # Use the calculated maximum instead.
    e_max = max_quant_error(r)
    log2n = math.log(n - 1, 2)

    f_dist = []  # results of cost function

    for i in range(len(h_dist)):
        entropy_norm = h_dist[i] / log2n
        quant_err_norm = e_dist[i] / e_max
        f = entropy_norm + quant_err_norm
        f_dist.append(f)

    return min(f_dist)
import os, sys, json
dirr = os.path.dirname(sys.argv[0])
filename = os.path.join(dirr, '../../libraries')
sys.path.append(filename)

dirr = os.path.dirname(sys.argv[0])
filename = os.path.join(dirr, '../imageProcess')
sys.path.append(filename)

import preprocessing, proportion, centroid

dirr = os.path.dirname(sys.argv[0])
filename = os.path.join(dirr, '../../../img/generated_canvas/verify_11.png')
img = preprocessing.preprocessing(filename)

proportion = proportion.proportion(img)
centroidX = centroid.centroid(img)[0]
centroidY = centroid.centroid(img)[1]

result = {
	'prop' : proportion,
	'centX' : centroidX,
	'centY' : centroidY,
}

print json.dumps(result)
Example #14
0
def main():
    preprocessing = False
    calculateConstant_x = 300
    calculateConstant_y = 615
    personLabelID = 15.00
    debug = True
    accuracyThreshold = 0.4
    RED = (0, 0, 255)
    YELLOW = (0, 255, 255)
    GREEN = (0, 255, 0)
    BLACK = (0, 0, 0)
    write_video = False

    if __name__ == "__main__":

        caffeNetwork = cv2.dnn.readNetFromCaffe("./SSD_MobileNet_prototxt.txt",
                                                "./SSD_MobileNet.caffemodel")
        cap = cv2.VideoCapture(0)
        # cap = cv2.VideoCapture("./vp.mp4")
        fourcc = cv2.VideoWriter_fourcc(*"XVID")
        # output_movie = cv2.VideoWriter("./result.avi", fourcc, 24, (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))

        while cap.isOpened():

            debug_frame, frame = cap.read()
            highRisk = set()
            mediumRisk = set()
            position = dict()
            detectionCoordinates = dict()

            if not debug_frame:
                # print("Video Error Gaes")
                break

            if preprocessing:
                frame = CLAHE(frame)
                print(frame)

            (imageHeight, imageWidth) = frame.shape[:2]
            pDetection = cv2.dnn.blobFromImage(
                cv2.resize(frame, (imageWidth, imageHeight)), 0.007843,
                (imageWidth, imageHeight), 127.5)

            caffeNetwork.setInput(pDetection)
            detections = caffeNetwork.forward()

            for i in range(detections.shape[2]):

                accuracy = detections[0, 0, i, 2]
                if accuracy > accuracyThreshold:

                    idOfClasses = int(detections[0, 0, i, 1])
                    box = detections[0, 0, i, 3:7] * np.array(
                        [imageWidth, imageHeight, imageWidth, imageHeight])
                    (startX, startY, endX, endY) = box.astype('int')

                    if idOfClasses == personLabelID:

                        boundBoxDefaultColor = (255, 255, 255)
                        cv2.rectangle(frame, (startX, startY), (endX, endY),
                                      boundBoxDefaultColor, 2)
                        detectionCoordinates[i] = (startX, startY, endX, endY)

                        centroid_x, centroid_y, boundBoxHeight = centroid(
                            startX, endX, startY, endY)
                        distance = calcDistance(boundBoxHeight)

                        centroid_x_centimeters = (
                            centroid_x * distance) / calculateConstant_y
                        centroid_y_centimeters = (
                            centroid_y * distance) / calculateConstant_y
                        position[i] = (centroid_x_centimeters,
                                       centroid_y_centimeters, distance)

            for i in position.keys():
                for j in position.keys():
                    if i < j:
                        distanceOfboundBoxes = sqrt(
                            pow(position[i][0] - position[j][0], 2) +
                            pow(position[i][1] - position[j][1], 2) +
                            pow(position[i][2] - position[j][2], 2))
                        if distanceOfboundBoxes < 150:  # jarak tidak aman
                            highRisk.add(i), highRisk.add(j)
                        elif distanceOfboundBoxes < 200 > 150:  # Jarak rawan
                            mediumRisk.add(i), mediumRisk.add(j)

            cv2.putText(frame,
                        "Sangat Rawan Penularan : " + str(len(highRisk)),
                        (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255),
                        2)
            cv2.putText(frame, "Rawan Penularan : " + str(len(mediumRisk)),
                        (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255),
                        2)
            cv2.putText(
                frame, "Jumlah Terdeteksi : " + str(len(detectionCoordinates)),
                (20, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

            drawResult(frame, position)
            if write_video:
                output_movie.write(frame)
            cv2.imshow('Dashboard Satpam', frame)
            waitkey = cv2.waitKey(1)
            if waitkey == ord("q"):
                break
Example #15
0
    POLYGON.backward(side)
    POLYGON.left(90)

    POLYGON.begin_fill()
    p1 = POLYGON.pos()
    POLYGON.forward(length_3 / 3)
    p2 = POLYGON.pos()
    POLYGON.right(120)
    POLYGON.forward(length_3 / 3)
    p3 = POLYGON.pos()
    POLYGON.right(90)
    POLYGON.forward(side)
    p4 = POLYGON.pos()
    vertex = (p1, p2, p3, p4)
    centro = centroid(vertex)

    alternate_color_1(i)
    sq = {'centro': centro, 'p1': p1, 'p2': p2, 'p3': p3, 'p4': p4}

    POLYGON.end_fill()
    COUNT += 1
    if i % 2 != 0:
        square_dict[naming[i][1][2] + naming[i][0][2]] = sq
    else:
        square_dict[naming[i][0][2] + naming[i][1][2]] = sq

    POLYGON.begin_fill()
    sq = square_3(length_3 / 3, side)
    alternate_color_2(i)
    POLYGON.end_fill()
Example #16
0
def subtract(flux1, time1, cadence, q, factor, cfilepath, centroid_type,
             cutoutdims, cluster, isolation):

    workingdir = os.getcwd()

    if centroid_type == 'e':
        os.chdir(cfilepath)
        centroids = np.loadtxt(f'{cluster}q{q}centroid.dat', delimiter=',')
        os.chdir(workingdir)
        x_shifts = centroids[:, 0]
        y_shifts = centroids[:, 1]

    # make mask first before cutting down flux
    mask = gaussmask(factor, flux1.shape[1], flux1.shape[2], isolation)

    # cut down both mask and flux, i.e. get rid of zeros
    flux1, mask = zerocutter(flux1, mask, factor)

    # prepare arrays/get dimensions etc
    if centroid_type == 'e':
        fluxnew, timenew, x_shifts, y_shifts = nc.nancleaner3d_c(
            flux1, time1, x_shifts, y_shifts)
    elif centroid_type == 't':
        fluxnew, timenew = nc.nancleaner3d(flux1, time1)
    dump, newcadence = nc.nancleaner3d(flux1, cadence)
    timespan = fluxnew.shape[0]

    # regridding
    oldy, oldx = fluxnew.shape[1], fluxnew.shape[2]  # reset dims
    newy, newx = fluxnew.shape[1] * factor, fluxnew.shape[2] * factor
    re_flux = np.zeros((timespan, newy, newx))
    shifted = np.zeros((timespan, newy, newx))

    nanmask = np.asarray(np.where(np.isnan(fluxnew) == True))
    rg_nanmask = np.array(
        (nanmask[0], nanmask[1] * factor, nanmask[2] * factor))

    for i in range(timespan):
        interpolant = spi.RectBivariateSpline(np.arange(oldy),
                                              np.arange(oldx),
                                              np.nan_to_num(fluxnew[i]),
                                              kx=1,
                                              ky=1)
        re_flux[i] = interpolant(np.linspace(0, oldy - 1, newy),
                                 np.linspace(0, oldx - 1,
                                             newx))  #/ (factor*factor)

    # regridding base cutout for plotting (oy vey)
    avg_original = np.nanmean(fluxnew, axis=0)
    regridded_base = rg.regrid(avg_original, factor)

    # centroiding
    originalmask = np.zeros(flux1[0].shape)  #+3
    originalmask[cutoutdims - 2:cutoutdims + 1,
                 cutoutdims - 2:cutoutdims + 1] += 3  # 3x3 box for checking
    mask_rg = rg.regrid_slow(originalmask, factor)
    if centroid_type == 't':
        x_cent, y_cent = ct.centroid(timespan, re_flux, mask_rg)
        midx, midy = (newx - 1) / 2, (newy - 1) / 2
        x_shifts = (x_cent - midx)
        y_shifts = (y_cent - midy)
    elif centroid_type == 'e':
        x_cent = 0
        y_cent = 0

    for i in range(timespan):
        interpolant = spi.RectBivariateSpline(np.arange(newy),
                                              np.arange(newx),
                                              re_flux[i, :, :],
                                              kx=1,
                                              ky=1)
        # interpolant = spi.interp2d(np.arange(newy), np.arange(newx), re_flux[i,:,:], kind='cubic')
        shifted[i, :, :] = interpolant(
            np.linspace(0 - y_shifts[i], newy - y_shifts[i], newy),
            np.linspace(0 - x_shifts[i], newx - x_shifts[i], newx))

    avgshift = np.nanmean(shifted, axis=0)

    # mask making
    maskrange = np.nanmax(avgshift) - np.nanmin(avgshift)
    # maskmax = np.nanmax(avgshift) - 0.5 * maskrange
    maskmin = np.nanmin(avgshift) + 0.05 * maskrange  # cut for background

    # defining six different standard masks
    # maskarr = np.zeros((6,newy,newx))
    # maskarr[0][(cutoutdims-1)*factor:cutoutdims*factor,(cutoutdims-1)*factor:cutoutdims*factor] +=1
    # maskarr[1][(cutoutdims-2)*factor:(cutoutdims+1)*factor,(cutoutdims-1)*factor:cutoutdims*factor] += 1
    # maskarr[1][(cutoutdims-1)*factor:cutoutdims*factor,(cutoutdims-2)*factor:(cutoutdims-1)*factor] += 1
    # maskarr[1][(cutoutdims-1)*factor:cutoutdims*factor,cutoutdims*factor:(cutoutdims+1)*factor] += 1
    # maskarr[2] += 1
    # maskarr[3] += circle(9, factor, oldy, oldx)
    # maskarr[4] += circle(5, factor, oldy, oldx)
    # maskarr[5] += circle(3, factor, oldy, oldx)
    # if mask != None:
    #    maskarr = np.delete(maskarr, np.delete(np.arange(6), mask), axis=0)

    # annulus
    mask_bg = np.zeros((newy, newx))
    counter = 0
    for index, val in np.ndenumerate(avgshift):
        if avgshift[index] < maskmin:  # and np.isnan(avgshift[index]) == False:
            mask_bg[index] = -1
            counter += 1

    # calculating background
    lclength = len(timenew)
    for j in range(lclength):
        bg = np.nansum(shifted[j][np.where(mask_bg == -1)])
        bg /= counter
        shifted[j] -= bg

    avgflux = np.nanmean(shifted, axis=0)  # new average image after
    output = np.c_[newcadence, timenew]

    new_flux = np.zeros(lclength)

    ap_av = np.nansum(avgflux * mask)
    for j in range(lclength):
        placeholder = shifted[j] - avgflux
        aperture = np.nansum(placeholder * mask)
        # annulus = sum(placeholder[np.where(mask==-1)])
        # annulus /= counter
        new_flux[j] = aperture + ap_av  #- annulus

    output = np.c_[output, new_flux]

    # for deprecated version with multiple masks:
    # for i in range(maskarr.shape[0]):
    #    new_flux = np.zeros(lclength)

    #    ap_av = np.nansum(avgflux[np.where(maskarr[i]==1)])
    #    for j in range(lclength):
    #       placeholder = shifted[j] - avgflux
    #       aperture = np.nansum(placeholder[np.where(maskarr[i]==1)])
    #       # annulus = sum(placeholder[np.where(mask==-1)])
    #       # annulus /= counter
    #       new_flux[j] = aperture + ap_av #- annulus

    #    output = np.c_[output, new_flux]

    return output, mask, avgflux, regridded_base, x_cent, y_cent  # prev maskarr
Example #17
0
    def __init__(self):
        # Manually set up our ROI for grabbing the hand.
        # Feel free to change these. I just chose the top right corner for filming.
        roi_top = 20
        roi_bottom = 140
        roi_right = 260
        roi_left = 380

        # ROI 2
        roi_top2 = 340
        roi_bottom2 = 460

        cam = cv2.VideoCapture(0)
        cam.set(3, 640)
        cam.set(4, 480)
        # Intialize a frame count
        num_frames = 0
        # background calc in real time
        # Start with a halfway point between 0 and 1 of accumulated weight
        accumulated_weight = 0.7
        accumulated_weight2 = 0.7
        accumulated_weight3 = 0.7
        background_calc = calc_accum()

        while True:
            # get the current frame
            ret, frame = cam.read()
            # flip the frame so that it is not the mirror view
            frame = cv2.flip(frame, 1)
            # clone the frame
            frame_copy = frame.copy()

            # object detection.
            height = frame_copy.shape[0]
            object_roi_top = height / 2
            object_roi_bottom = 640
            object_detect = frame[object_roi_top:object_roi_bottom, :]
            object_gray = cv2.cvtColor(object_detect, cv2.COLOR_BGR2GRAY)
            object_gray = cv2.GaussianBlur(object_gray, (5, 5), 0)

            # ROI 1
            # Grab the ROI from the frame(1)
            roi = frame[roi_top:roi_bottom, roi_right:roi_left]
            gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
            # Apply grayscale and blur to ROI
            gray = cv2.GaussianBlur(gray, (5, 5), 0)

            # ROI 2
            roi2 = frame[roi_top2:roi_bottom2, roi_right:roi_left]
            gray2 = cv2.cvtColor(roi2, cv2.COLOR_BGR2GRAY)
            gray2 = cv2.GaussianBlur(gray2, (5, 5), 0)

            # For the first 60 frames we will calculate the average of the background.
            if num_frames < 60:
                background_calc.calc_accum_avg(gray, accumulated_weight)
                background_calc.calc_accum_avg2(gray2, accumulated_weight2)
                background_calc.calc_accum_avg3(object_gray,
                                                accumulated_weight3)
                if num_frames <= 59:
                    cv2.putText(frame_copy, "WAIT! GETTING BACKGROUND AVG.",
                                (1, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)
                    cv2.imshow("Vision", frame_copy)
            else:

                # shape detect upper
                upper_shape = segment(gray)
                if upper_shape is not None:
                    upper_thresh, upper_contour, upper_segment, upper_cnts = upper_shape
                    upper_shape_detect = detect(upper_contour)
                    # Apply hough transform on the image
                    (upper_cX, upper_cY, upper_c) = centroid(upper_cnts)

                    cv2.drawContours(frame_copy,
                                     [upper_segment + (roi_right, roi_top)],
                                     -1, (255, 0, 0), 1)
                    cv2.circle(frame_copy,
                               (upper_cX + roi_right, roi_top + upper_cY), 7,
                               (255, 0, 0), -1)
                    cv2.putText(frame_copy,
                                "upper_shape : " + str(upper_shape_detect),
                                (1, 440), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)

                    cv2.imshow("upper_threshold", upper_thresh)
                    # shape detect bottom
                bottom_shape = segment(gray2)
                if bottom_shape is not None:
                    bottom_thresh, bottom_contour, bottom_segment, bottom_cnts = bottom_shape
                    bottom_shape_detect = detect(bottom_contour)
                    (bottom_cX, bottom_cY, bottom_c) = centroid(bottom_cnts)

                    cv2.drawContours(frame_copy,
                                     [bottom_segment + (roi_right, roi_top2)],
                                     -1, (255, 0, 0), 1)
                    cv2.putText(frame_copy,
                                "bottom_shape : " + str(bottom_shape_detect),
                                (1, 460), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)
                    cv2.circle(frame_copy,
                               (bottom_cX + roi_right, roi_top2 + bottom_cY),
                               7, (255, 0, 0), -1)
                    cv2.imshow("bottom_threshold", bottom_thresh)

                # distance
                upper_c = (upper_cX + roi_right, roi_top + upper_cY)
                bottom_c = (bottom_cX + roi_right, roi_top2 + bottom_cY)
                roi_distance = distance(upper_c, bottom_c)
                cv2.putText(frame_copy,
                            "ROI DISTANCE={} ".format(roi_distance), (1, 400),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

                if upper_shape_detect == "square" or "rectangle" and bottom_shape_detect == "square" or "rectangle":
                    angles = rotation(bottom_c, upper_c)
                    cv2.putText(frame_copy, "difference ={}".format(angles),
                                (1, 420), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)
                object_detect = segment(object_gray)
                if object_detect is not None:
                    object_thresh, object_contour, object_segment, object_cnts = object_detect
                    multi_obejct_detect = multi_detect()
                    multi_obejct_detect.detect(
                        frame_copy[object_roi_top:object_roi_bottom, :],
                        object_contour)

    # Draw ROI Rectangle on frame copy
            cv2.rectangle(frame_copy, (roi_left, roi_top),
                          (roi_right, roi_bottom), (0, 0, 255), 5)
            cv2.rectangle(frame_copy, (roi_left, roi_top2),
                          (roi_right, roi_bottom2), (0, 0, 255), 5)

            # increment the number of frames for tracking
            num_frames += 1
            #print(distance(upper_c,bottom_c))

            # Display the frame with segmented hand
            cv2.imshow("Vision", frame_copy)

            # Close windows with Esc
            k = cv2.waitKey(1) & 0xFF

            if k == 27:
                break
        cam.release()
        cv2.destroyAllWindows()
Example #18
0
Rx, Ry = Bezier(list(zip(Rxc, Ryc))).T
RunningVolume = RunningVolume - RimSubtract(Rx, Ry)
for i in range(0, len(Cdata)):
    Cxc = np.append(Cxc, Cdata[i, 0])
    Cyc = np.append(Cyc, Cdata[i, 1])
Cx, Cy = Bezier(list(zip(Cxc, Cyc))).T
RunningVolume = RunningVolume - CupSubtract(Cx, Cy)
density = Sdata[7] / (10**(9))
halfmass = RunningVolume * density * (10**3)
# This populates matrices for plotting
megamatx, megamaty, prof, rim, cup, bulkmat = Bulkmat(Px, Py, Rx, Ry, Cx, Cy,
                                                      Bdata, Pdata, Rdata,
                                                      Cdata)
#Creates coordinate pair that makes up physical location of centroid of
#... 2d quarter section, and computes RimWeightRatio
Cx, Cy, RimWeightRatio = centroid(bulkmat)
# CHECKING MINIMUM WALL THICKNESS AGAINST SPECIFIED ALLOWABLE MINIMUM
floatingminthick = minthick(Bdata, Sdata, prof, rim, cup)
thick_criteria = Sdata[8]  #this is in millimeters
# ERROR CHECKING OCCURS IN THIS SECTION
# IF AN ERROR OCCURS, THEN THE BREAKFLAG, HEREFORTH SET EQUAL TO ZERO,
# ... WILL BE SET EQUAL TO A NON-ZERO VALUE
thickflag = 0
if floatingminthick <= thick_criteria:
    thickflag = 1
    print("ERRROR: YOUR DESIGN VIOLATES MINIMUM WALL THICKNESS")
    print("THIS CAN EITHER BE DUE TO SELF INTERSECTION, OR A GENUINELY")
    print("TOO THIN WALL.")
    #Yeah, this ain't workin, yet.
    farea = fracturearea(floatingminthick, thick_criteria, Sdata, prof, rim,
                         cup)
times = json.loads(sys.argv[1])
NUMDEVS = 3
imgArray = ['filename_1.png', 'filename_2.png', 'filename_3.png', 'filename_4.png', 'filename_5.png', 'filename_6.png', 'filename_7.png', 'filename_8.png', 'filename_9.png', 'filename_10.png']
dirr = os.path.dirname(sys.argv[0])
filename = os.path.abspath(os.path.join(dirr, '../../../img/generated_canvas'))
centroidsX = []
centroidsY = []
proportions = []

for img in imgArray:
	fileTemp = os.path.join(filename, img)
	imgTemp = preprocessing.preprocessing(fileTemp)
	imgTemp.save('fart.png')
	proportions.append(proportion.proportion(imgTemp))
	centroidsX.append(centroid.centroid(imgTemp)[0])
	centroidsY.append(centroid.centroid(imgTemp)[1])


meanProps, devProps = meanStDev.meanStDev(proportions)
meanCentsX, devCentsX = meanStDev.meanStDev(centroidsX)
meanCentsY, devCentsY = meanStDev.meanStDev(centroidsY)
meanTimes, devTimes = meanStDev.meanStDev(times)

minProps = meanProps - (NUMDEVS * devProps)
maxProps = meanProps + (NUMDEVS * devProps)
resultsProps = [minProps, maxProps]

minCentsX = meanCentsX - (NUMDEVS * devCentsX)
maxCentsX = meanCentsX + (NUMDEVS * devCentsX)
resultsCentsX = [minCentsX, maxCentsX]