Beispiel #1
0
def Speed(old_frame, pts, frame, frame_anterior, rate, fps):
    frame = np.asarray(frame)
    mask = np.zeros(shape=frame.shape[0:2])
    for dic in old_frame:
        mask[dic['topleft']['y']:dic['bottomright']['y'],
             dic['topleft']['x']:dic['bottomright']['x']] = dic['id']
    mask_h, M = perspective.four_point_transform(mask, pts)
    frame_h, M = perspective.four_point_transform(frame, pts)
    frame_ah, M = perspective.four_point_transform(frame_anterior, pts)
    for i in range(len(old_frame)):
        binary = (mask_h == old_frame[i]['id'])
        cv2.imwrite('old.png', frame_ah)
        cv2.imwrite('new.png', frame_h)
        os.system('./deepflow2 old.png new.png sintel.flo')
        file = 'sintel.flo'
        flow = read(file)
        mod = np.linalg.norm(flow, axis=2)
        plt.imsave('opticalflow/' + str(framen - 1) + '.png', mod)
        velocidad = float(np.mean(mod[binary == True]) * fps / rate * 3.6)
        if (velocidad > (np.mean(old_frame[i]['speed']) / 2)) | (
                not old_frame[i]['speed']):
            old_frame[i]['speed'].append(velocidad)
        else:
            old_frame[i]['speed'].append(np.mean(old_frame[i]['speed']))
    return old_frame, M
def main(flowfileFolder, outputPath):
    list = os.listdir(flowfileFolder)  # dir is your directory path
    number_files = len(list)
    print(number_files)

    video = cv2.VideoWriter(outputPath,
                            cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30,
                            (800, 410))

    for i in range(number_files):
        index = (i + 1) * 3
        flowPath = os.path.join(flowfileFolder, 'flow%d.flo' % index)
        flow = readFlowFile.read(flowPath)

        img = computeImg(flow)
        video.write(img)
        # cv2.imshow('flow', img)
        # cv2.waitKey()

    video.release()
Beispiel #3
0
    rad = np.sqrt(np.multiply(u, u) + np.multiply(v, v))
    maxrad = max([maxrad, np.amax(rad)])
    print('max flow: %.4f flow range: u = %.3f .. %.3f; v = %.3f .. %.3f\n' %
          (maxrad, minu, maxu, minv, maxv))

    u = u / (maxrad + eps)
    v = v / (maxrad + eps)
    img = computeColor(u, v)
    return img


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--flowfile',
                        type=str,
                        default='colorTest.flo',
                        help='Flow file')
    parser.add_argument('--write',
                        type=bool,
                        default=False,
                        help='write flow as png')
    file = parser.parse_args().flowfile
    flow = readFlowFile.read(file)
    flow /= 6
    print(flow.shape)
    img = computeImg(flow)
    #cv2.imshow(file, img)
    k = cv2.waitKey()
    if parser.parse_args().write:
        cv2.imwrite(file[:-4] + '.png', img)
Beispiel #4
0
    file.close()


    dirName = ""
    totalMagField = []
    temp = []  # temporal : List of frame magnitude, spatial : Field of pixel magnitude
    pixel = 0
    maxMag = np.inf
    aveMag = np.inf

    for i in range(0, 400):
        
        fileName = "C:/Project/COG/ABMCTS-OF/flow_" + str(i) + "_" + str(i+1) + ".flo"
        if os.path.isfile(fileName):
        #### Main Calculation Starts
            flowField = readFlowFile.read(fileName)
        # Get magnitude of each vector and apply filter
            magField = GetMagField(flowField)
            if (temp == []):
                temp = magField
            else:
            # Sum up all the magnitude fields into one field.
                temp = temp + magField
            # os.remove(fileName)
            # if (os.path.isfile(str(i+1)+".png")):
            #     os.remove(str(i+1)+".png")

# Getting total displacement by adding all the magnitudes.
    # print (temp)
    totalDisplacement = float(sum(sum(temp)))
    temp = np.array(temp)
Beispiel #5
0
u = x * range_f / s2 - range_f
v = y * range_f / s2 - range_f

img = computeColor.computeColor(u / truerange, v / truerange)

img[s2, :, :] = 0
img[:, s2, :] = 0

cv2.imshow('test color pattern', img)
k = cv2.waitKey()

F = np.stack((u, v), axis=2)
writeFlowFile.write(F, 'colorTest.flo')

flow = readFlowFile.read('colorTest.flo')

u = flow[:, :, 0]
v = flow[:, :, 1]

img = computeColor.computeColor(u / truerange, v / truerange)

img[s2, :, :] = 0
img[:, s2, :] = 0

cv2.imshow('saved and reloaded test color pattern', img)
k = cv2.waitKey()

# color encoding scheme for optical flow
img = computeColor.computeColor(u / range_f / math.sqrt(2),
                                v / range_f / math.sqrt(2))
Beispiel #6
0
    u = x * range_f / s2 - range_f
    v = y * range_f / s2 - range_f

    img = computeColor.computeColor(u / truerange, v / truerange)

    img[s2, :, :] = 0
    img[:, s2, :] = 0

    cv2.imshow("Test color pattern", img)
    k = cv2.waitKey()

    F = np.stack((u, v), axis=2)
    writeFlowFile.write(F, Path("colorTest.flo"))

    flow = readFlowFile.read(Path("colorTest.flo"))

    u = flow[:, :, 0]
    v = flow[:, :, 1]

    img = computeColor.computeColor(u / truerange, v / truerange)

    img[s2, :, :] = 0
    img[:, s2, :] = 0

    cv2.imshow("Saved and reloaded test color pattern", img)
    k = cv2.waitKey()

    # Color encoding scheme for optical flow
    img = computeColor.computeColor(u / range_f / math.sqrt(2),
                                    v / range_f / math.sqrt(2))
	rad = np.sqrt(np.multiply(u, u) + np.multiply(v, v))
	maxrad = max([maxrad, np.amax(rad)])
	print(f"max flow:")
	print(f"  {maxrad:.4f}")
	print(f"flow range:")
	print(f"  u = {minu:.3f} .. {maxu:.3f}")
	print(f"  v = {minv:.3f} .. {maxv:.3f}")

	u = u / (maxrad + eps)
	v = v / (maxrad + eps)
	img = computeColor(u, v)

	return img


# ==================================================================================================
if (__name__ == "__main__"):
	import readFlowFile

	parser = argparse.ArgumentParser()
	parser.add_argument("flow_file", type=str, default="colorTest.flo", help="Flow file")
	parser.add_argument("--write", action="store_true", help="Write flow as PNG")
	args = parser.parse_args()
	args.flow_file = Path(args.flow_file)
	flow = readFlowFile.read(args.flow_file)
	img = computeImg(flow)
	cv2.imshow(str(args.flow_file), img)
	k = cv2.waitKey()
	if parser.parse_args().write:
		cv2.imwrite(str(args.flow_file.with_suffix(".png")), img)