org.bytedeco.javacpp.Loader Java Examples

The following examples show how to use org.bytedeco.javacpp.Loader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LivePlayTest3.java    From oim-fx with MIT License 6 votes vote down vote up
public void run() {
	Loader.load(opencv_objdetect.class);

	try {
		grabber = FFmpegFrameGrabber.createDefault(url);
		grabber.start();
	} catch (Exception e) {
		try {
			grabber.restart();
		} catch (Exception e1) {
		}
	}
	while (true) {
		// try {
		getBufferedImage();
		// sleep(1);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
	}
}
 
Example #2
Source File: Nd4jBlas.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
public Nd4jBlas() {
    int numThreads;
    String skipper = System.getenv(ND4JEnvironmentVars.ND4J_SKIP_BLAS_THREADS);
    if (skipper == null || skipper.isEmpty()) {
        String numThreadsString = System.getenv(ND4JEnvironmentVars.OMP_NUM_THREADS);
        if (numThreadsString != null && !numThreadsString.isEmpty()) {
            numThreads = Integer.parseInt(numThreadsString);
            setMaxThreads(numThreads);
        } else {
            int cores = Loader.totalCores();
            int chips = Loader.totalChips();
            if (cores > 0 && chips > 0)
                numThreads = Math.max(1, cores / chips);
            else
                numThreads = NativeOpsHolder.getCores(Runtime.getRuntime().availableProcessors());
            setMaxThreads(numThreads);
        }

        String logInit = System.getProperty(ND4JSystemProperties.LOG_INITIALIZATION);
        if(logOpenMPBlasThreads() && (logInit == null || logInit.isEmpty() || Boolean.parseBoolean(logInit))) {
            log.info("Number of threads used for OpenMP BLAS: {}", getMaxThreads());
        }
    }
}
 
Example #3
Source File: FFmpegFrameFilter.java    From VideoAndroid with Apache License 2.0 6 votes vote down vote up
public static void tryLoad() throws Exception {
    if (loadingException != null) {
        throw loadingException;
    } else {
        try {
            Loader.load(org.bytedeco.javacpp.avutil.class);
            Loader.load(org.bytedeco.javacpp.avcodec.class);
            Loader.load(org.bytedeco.javacpp.avformat.class);
            Loader.load(org.bytedeco.javacpp.postproc.class);
            Loader.load(org.bytedeco.javacpp.swresample.class);
            Loader.load(org.bytedeco.javacpp.swscale.class);
            Loader.load(org.bytedeco.javacpp.avfilter.class);

            av_register_all();
            avfilter_register_all();
        } catch (Throwable t) {
            if (t instanceof Exception) {
                throw loadingException = (Exception)t;
            } else {
                throw loadingException = new Exception("Failed to load " + FFmpegFrameRecorder.class, t);
            }
        }
    }
}
 
Example #4
Source File: FFmpegFrameRecorder.java    From VideoAndroid with Apache License 2.0 6 votes vote down vote up
public static void tryLoad() throws Exception {
    if (loadingException != null) {
        throw loadingException;
    } else {
        try {
            Loader.load(org.bytedeco.javacpp.avutil.class);
            Loader.load(org.bytedeco.javacpp.swresample.class);
            Loader.load(org.bytedeco.javacpp.avcodec.class);
            Loader.load(org.bytedeco.javacpp.avformat.class);
            Loader.load(org.bytedeco.javacpp.swscale.class);

            /* initialize libavcodec, and register all codecs and formats */
            av_register_all();
            avformat_network_init();
        } catch (Throwable t) {
            if (t instanceof Exception) {
                throw loadingException = (Exception)t;
            } else {
                throw loadingException = new Exception("Failed to load " + FFmpegFrameRecorder.class, t);
            }
        }
    }
}
 
Example #5
Source File: Nd4jBlas.java    From nd4j with Apache License 2.0 6 votes vote down vote up
public Nd4jBlas() {
    int numThreads;
    String skipper = System.getenv("ND4J_SKIP_BLAS_THREADS");
    if (skipper == null || skipper.isEmpty()) {
        String numThreadsString = System.getenv("OMP_NUM_THREADS");
        if (numThreadsString != null && !numThreadsString.isEmpty()) {
            numThreads = Integer.parseInt(numThreadsString);
            setMaxThreads(numThreads);
        } else {
            int cores = Loader.totalCores();
            int chips = Loader.totalChips();
            if (cores > 0 && chips > 0)
                numThreads = Math.max(1, cores / chips);
            else
                numThreads = NativeOps.getCores(Runtime.getRuntime().availableProcessors());
            setMaxThreads(numThreads);
        }
        log.info("Number of threads used for BLAS: {}", getMaxThreads());
    }
}
 
Example #6
Source File: NativeOpsHolder.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
private NativeOpsHolder() {
    try {
        Properties props = Nd4jContext.getInstance().getConf();

        String name = System.getProperty(Nd4j.NATIVE_OPS, props.get(Nd4j.NATIVE_OPS).toString());
        Class<? extends NativeOps> nativeOpsClazz = Class.forName(name).asSubclass(NativeOps.class);
        deviceNativeOps = nativeOpsClazz.newInstance();

        deviceNativeOps.initializeDevicesAndFunctions();
        int numThreads;
        String numThreadsString = System.getenv(ND4JEnvironmentVars.OMP_NUM_THREADS);
        if (numThreadsString != null && !numThreadsString.isEmpty()) {
            numThreads = Integer.parseInt(numThreadsString);
            deviceNativeOps.setOmpNumThreads(numThreads);
        } else {
            int cores = Loader.totalCores();
            int chips = Loader.totalChips();
            if (chips > 0 && cores > 0) {
                deviceNativeOps.setOmpNumThreads(Math.max(1, cores / chips));
            } else
                deviceNativeOps.setOmpNumThreads(
                                getCores(Runtime.getRuntime().availableProcessors()));
        }
        //deviceNativeOps.setOmpNumThreads(4);

        String logInitProperty = System.getProperty(ND4JSystemProperties.LOG_INITIALIZATION, "true");
        boolean logInit = Boolean.parseBoolean(logInitProperty);

        if(logInit) {
            log.info("Number of threads used for linear algebra: {}", deviceNativeOps.ompGetMaxThreads());
        }
    } catch (Exception | Error e) {
        throw new RuntimeException(
                        "ND4J is probably missing dependencies. For more information, please refer to: https://deeplearning4j.konduit.ai/nd4j/backend",
                        e);
    }
}
 
Example #7
Source File: OnnxModelLoader.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
@Override
public Session loadModel() throws Exception {
    Env env = new Env(ORT_LOGGING_LEVEL_WARNING, new BytePointer("konduit-serving-onnx-session" + System.currentTimeMillis()));

    try (SessionOptions sessionOptions = new SessionOptions()) {
        try (Pointer bp = Loader.getPlatform().toLowerCase().startsWith("windows") ? new CharPointer(modelPath) : new BytePointer(modelPath)) {
            return new Session(env, bp, sessionOptions);
        }
    }
}
 
Example #8
Source File: JCublasBackend.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canRun() {
    int[] count = { 0 };
    org.bytedeco.cuda.global.cudart.cudaGetDeviceCount(count);
    if (count[0] <= 0) {
        throw new RuntimeException("No CUDA devices were found in system");
    }
    Loader.load(org.bytedeco.cuda.global.cublas.class);

    return true;
}
 
Example #9
Source File: Nd4jCudaPresets.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Override public void init(ClassProperties properties) {
    String platform = properties.getProperty("platform");
    List<String> preloads = properties.get("platform.preload");
    List<String> resources = properties.get("platform.preloadresource");

    // Only apply this at load time since we don't want to copy the CUDA libraries here
    if (!Loader.isLoadLibraries()) {
        return;
    }
    int i = 0;
    String[] libs = {"cudart", "cublasLt", "cublas", "cusolver", "cusparse", "cudnn"};
    for (String lib : libs) {
        switch (platform) {
            case "linux-arm64":
            case "linux-ppc64le":
            case "linux-x86_64":
            case "macosx-x86_64":
                lib += lib.equals("cudnn") ? "@.7" : lib.equals("cudart") ? "@.10.2" : "@.10";
                break;
            case "windows-x86_64":
                lib += lib.equals("cudnn") ? "64_7" : lib.equals("cudart") ? "64_102" : "64_10";
                break;
            default:
                continue; // no CUDA
        }
        if (!preloads.contains(lib)) {
            preloads.add(i++, lib);
        }
    }
    if (i > 0) {
        resources.add("/org/bytedeco/cuda/");
    }
}
 
Example #10
Source File: TestNativeImageLoader.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
org.opencv.core.Mat makeRandomOrgOpenCvCoreMatImage(int height, int width, int channels) {
    Mat img = makeRandomImage(height, width, channels);

    Loader.load(org.bytedeco.opencv.opencv_java.class);
    OpenCVFrameConverter.ToOrgOpenCvCoreMat c = new OpenCVFrameConverter.ToOrgOpenCvCoreMat();

    return c.convert(c.convert(img));
}
 
Example #11
Source File: NativeOpsHolder.java    From nd4j with Apache License 2.0 5 votes vote down vote up
private NativeOpsHolder() {
    try {
        Properties props = Nd4jContext.getInstance().getConf();

        String name = System.getProperty(Nd4j.NATIVE_OPS, props.get(Nd4j.NATIVE_OPS).toString());
        Class<? extends NativeOps> nativeOpsClazz = Class.forName(name).asSubclass(NativeOps.class);
        deviceNativeOps = nativeOpsClazz.newInstance();

        deviceNativeOps.initializeDevicesAndFunctions();
        int numThreads;
        String numThreadsString = System.getenv("OMP_NUM_THREADS");
        if (numThreadsString != null && !numThreadsString.isEmpty()) {
            numThreads = Integer.parseInt(numThreadsString);
            deviceNativeOps.setOmpNumThreads(numThreads);
        } else {
            int cores = Loader.totalCores();
            int chips = Loader.totalChips();
            if (chips > 0 && cores > 0) {
                deviceNativeOps.setOmpNumThreads(Math.max(1, cores / chips));
            } else
                deviceNativeOps.setOmpNumThreads(
                                deviceNativeOps.getCores(Runtime.getRuntime().availableProcessors()));
        }
        //deviceNativeOps.setOmpNumThreads(4);

        log.info("Number of threads used for NativeOps: {}", deviceNativeOps.ompGetMaxThreads());
    } catch (Exception | Error e) {
        throw new RuntimeException(
                        "ND4J is probably missing dependencies. For more information, please refer to: http://nd4j.org/getstarted.html",
                        e);
    }
}
 
Example #12
Source File: JCublasBackend.java    From nd4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canRun() {
    int[] count = { 0 };
    cuda.cudaGetDeviceCount(count);
    if (count[0] <= 0) {
        throw new RuntimeException("No CUDA devices were found in system");
    }
    Loader.load(cublas.class);
    return true;
}
 
Example #13
Source File: Builder.java    From tapir with MIT License 5 votes vote down vote up
/** Sets the {@link #properties} field to the ones loaded from resources for the specified platform. */
public Builder properties(String platform) {
    if (platform != null) {
        properties = Loader.loadProperties(platform);
    }
    return this;
}
 
Example #14
Source File: Builder.java    From tapir with MIT License 5 votes vote down vote up
/**
 * Constructor that simply initializes everything.
 * @param logger where to send messages
 */
public Builder(Logger logger) {
    this.logger = logger;
    System.setProperty("org.bytedeco.javacpp.loadlibraries", "false");
    properties = Loader.loadProperties();
    classScanner = new ClassScanner(logger, new LinkedList<Class>(),
            new UserClassLoader(Thread.currentThread().getContextClassLoader()));
    compilerOptions = new LinkedList<String>();
}
 
Example #15
Source File: FaceDetector.java    From ExoVisix with MIT License 5 votes vote down vote up
public void setClassifierUpperBody(String name) {

		try {

			classiferName = name;
			classifierFile = Loader.extractResource(classiferName, null, "classifier", ".xml");

			if (classifierFile == null || classifierFile.length() <= 0) {
				throw new IOException("Could not extract \"" + classiferName + "\" from Java resources.");
			}

			// Preload the opencv_objdetect module to work around a known bug.
			Loader.load(opencv_objdetect.class);
			classifierUpperBody = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
			classifierFile.delete();
			if (classifier.isNull()) {
				throw new IOException("Could not load the classifier file.");
			}

		} catch (Exception e) {
			if (exception == null) {
				exception = e;

			}
		}

	}
 
Example #16
Source File: FaceDetector.java    From ExoVisix with MIT License 5 votes vote down vote up
public void setClassifierEyeGlass(String name) {

		try {

			setClassiferName(name);
			classifierFile = Loader.extractResource(classiferName, null, "classifier", ".xml");

			if (classifierFile == null || classifierFile.length() <= 0) {
				throw new IOException("Could not extract \"" + classiferName + "\" from Java resources.");
			}

			// Preload the opencv_objdetect module to work around a known bug.
			Loader.load(opencv_objdetect.class);
			classifierEyeglass = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
			classifierFile.delete();
			if (classifier.isNull()) {
				throw new IOException("Could not load the classifier file.");
			}

		} catch (Exception e) {
			if (exception == null) {
				exception = e;

			}
		}

	}
 
Example #17
Source File: FaceDetector.java    From ExoVisix with MIT License 5 votes vote down vote up
public void setClassifierFullBody(String name) {

		try {

			setClassiferName(name);
			classifierFile = Loader.extractResource(classiferName, null, "classifier", ".xml");

			if (classifierFile == null || classifierFile.length() <= 0) {
				throw new IOException("Could not extract \"" + classiferName + "\" from Java resources.");
			}

			// Preload the opencv_objdetect module to work around a known bug.
			Loader.load(opencv_objdetect.class);
			classifierFullBody = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
			classifierFile.delete();
			if (classifier.isNull()) {
				throw new IOException("Could not load the classifier file.");
			}

		} catch (Exception e) {
			if (exception == null) {
				exception = e;

			}
		}

	}
 
Example #18
Source File: FaceDetector.java    From ExoVisix with MIT License 5 votes vote down vote up
public void setClassifierSideFace(String name) {

		try {

			classiferName = name;
			classifierFile = Loader.extractResource(classiferName, null, "classifier", ".xml");

			if (classifierFile == null || classifierFile.length() <= 0) {
				throw new IOException("Could not extract \"" + classiferName + "\" from Java resources.");
			}

			// Preload the opencv_objdetect module to work around a known bug.
			Loader.load(opencv_objdetect.class);
			classifierSideFace = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
			classifierFile.delete();
			if (classifier.isNull()) {
				throw new IOException("Could not load the classifier file.");
			}

		} catch (Exception e) {
			if (exception == null) {
				exception = e;

			}
		}

	}
 
Example #19
Source File: FaceDetector.java    From ExoVisix with MIT License 5 votes vote down vote up
public void setClassifierSmile(String name) {

		try {

			setClassiferName(name);
			classifierFile = Loader.extractResource(classiferName, null, "classifier", ".xml");

			if (classifierFile == null || classifierFile.length() <= 0) {
				throw new IOException("Could not extract \"" + classiferName + "\" from Java resources.");
			}

			// Preload the opencv_objdetect module to work around a known bug.
			Loader.load(opencv_objdetect.class);
			classifierSmile = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
			classifierFile.delete();
			if (classifier.isNull()) {
				throw new IOException("Could not load the classifier file.");
			}

		} catch (Exception e) {
			if (exception == null) {
				exception = e;

			}
		}

	}
 
Example #20
Source File: FaceDetector.java    From ExoVisix with MIT License 5 votes vote down vote up
public void setClassifierEye(String name) {

		try {

			classiferName = name;
			classifierFile = Loader.extractResource(classiferName, null, "classifier", ".xml");

			if (classifierFile == null || classifierFile.length() <= 0) {
				throw new IOException("Could not extract \"" + classiferName + "\" from Java resources.");
			}

			// Preload the opencv_objdetect module to work around a known bug.
			Loader.load(opencv_objdetect.class);
			classifierEye = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
			classifierFile.delete();
			if (classifier.isNull()) {
				throw new IOException("Could not load the classifier file.");
			}

		} catch (Exception e) {
			if (exception == null) {
				exception = e;

			}
		}

	}
 
Example #21
Source File: FaceDetector.java    From ExoVisix with MIT License 5 votes vote down vote up
public void setClassifier(String name) {

		try {

			setClassiferName(name);
			classifierFile = Loader.extractResource(classiferName, null, "classifier", ".xml");

			if (classifierFile == null || classifierFile.length() <= 0) {
				throw new IOException("Could not extract \"" + classiferName + "\" from Java resources.");
			}

			// Preload the opencv_objdetect module to work around a known bug.
			Loader.load(opencv_objdetect.class);
			classifier = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
			classifierFile.delete();
			if (classifier.isNull()) {
				throw new IOException("Could not load the classifier file.");
			}

		} catch (Exception e) {
			if (exception == null) {
				exception = e;

			}
		}

	}
 
Example #22
Source File: FFmpegFrameRecorderPlus.java    From easyCV with Apache License 2.0 5 votes vote down vote up
public static void tryLoad() throws Exception {
    if (loadingException != null) {
        throw loadingException;
    } else {
        try {
            Loader.load(org.bytedeco.javacpp.avutil.class);
            Loader.load(org.bytedeco.javacpp.swresample.class);
            Loader.load(org.bytedeco.javacpp.avcodec.class);
            Loader.load(org.bytedeco.javacpp.avformat.class);
            Loader.load(org.bytedeco.javacpp.swscale.class);

            /* initialize libavcodec, and register all codecs and formats */
            av_jni_set_java_vm(Loader.getJavaVM(), null);
            avcodec_register_all();
            av_register_all();
            avformat_network_init();

            Loader.load(org.bytedeco.javacpp.avdevice.class);
            avdevice_register_all();
        } catch (Throwable t) {
            if (t instanceof Exception) {
                throw loadingException = (Exception)t;
            } else {
                throw loadingException = new Exception("Failed to load " + FFmpegFrameRecorder.class, t);
            }
        }
    }
}
 
Example #23
Source File: GridWorldDQN.java    From burlap_caffe with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {

        // Learning constants
        double gamma = 0.99;
        int replayStartSize = 50000;
        int memorySize = 1000000;
        double epsilonStart = 1;
        double epsilonEnd = 0.1;
        double testEpsilon = 0.05;
        int epsilonAnnealDuration = 1000000;
        int staleUpdateFreq = 10000;

        // Caffe solver file
        String solverFile = "example_models/grid_world_dqn_solver.prototxt";

        // Load Caffe
        Loader.load(caffe.Caffe.class);

        // Setup the network
        GridWorldDQN gridWorldDQN = new GridWorldDQN(solverFile, gamma);

        // Create the policies
        SolverDerivedPolicy learningPolicy =
                new AnnealedEpsilonGreedy(epsilonStart, epsilonEnd, epsilonAnnealDuration);
        SolverDerivedPolicy testPolicy = new EpsilonGreedy(testEpsilon);

        // Setup the learner
        DeepQLearner deepQLearner =
                new DeepQLearner(gridWorldDQN.domain, gamma, replayStartSize, learningPolicy, gridWorldDQN.dqn);
        deepQLearner.setExperienceReplay(new FixedSizeMemory(memorySize), gridWorldDQN.dqn.batchSize);
        deepQLearner.useStaleTarget(staleUpdateFreq);

        // Setup the tester
        Tester tester = new SimpleTester(testPolicy);

        // Set the QProvider for the policies
        learningPolicy.setSolver(deepQLearner);
        testPolicy.setSolver(deepQLearner);

        // Setup the visualizer
        VisualExplorer exp = new VisualExplorer(
                gridWorldDQN.domain, gridWorldDQN.env, GridWorldVisualizer.getVisualizer(gridWorldDQN.gwdg.getMap()));
        exp.initGUI();
        exp.startLiveStatePolling(33);

        // Setup helper
        TrainingHelper helper = new TrainingHelper(
                deepQLearner, tester, gridWorldDQN.dqn, actionSet, gridWorldDQN.env);
        helper.setTotalTrainingSteps(50000000);
        helper.setTestInterval(500000);
        helper.setTotalTestSteps(125000);
        helper.setMaxEpisodeSteps(10000);

        // Run helper
        helper.run();
    }
 
Example #24
Source File: TestFrameExperienceMemory.java    From burlap_caffe with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() {
    Loader.load(opencv_core.class);
}
 
Example #25
Source File: AtariDQN.java    From burlap_caffe with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

        // Learning constants defined in the DeepMind Nature paper
        // (http://www.nature.com/nature/journal/v518/n7540/full/nature14236.html)
        int experienceMemoryLength = 1000000;
        int maxHistoryLength = 4;
        int staleUpdateFreq = 10000;
        double gamma = 0.99;
        int frameSkip = 4;
        int updateFreq = 4;
        double rewardClip = 1.0;
        float gradientClip = 1.0f;
        double epsilonStart = 1;
        double epsilonEnd = 0.1;
        int epsilonAnnealDuration = 1000000;
        int replayStartSize = 50000;
        int noopMax = 30;
        int totalTrainingSteps = 50000000;
        double testEpsilon = 0.05;

        // Testing and recording constants
        int testInterval = 250000;
        int totalTestSteps = 125000;
        int maxEpisodeSteps = 100000;
        int snapshotInterval = 1000000;
        String snapshotPrefix = "snapshots/experiment1";
        String resultsDirectory = "results/experiment1";

        // ALE Paths
        // TODO: Set to appropriate paths for your machine
        String alePath = "/path/to/atari/executable";
        String romPath = "/path/to/atari/rom/file";

        // Caffe solver file
        String solverFile = "example_models/atari_dqn_solver.prototxt";

        // Load Caffe
        Loader.load(Caffe.class);

        // Create the domain
        ALEDomainGenerator domGen = new ALEDomainGenerator(ALEDomainGenerator.saActionSet());
        SADomain domain = domGen.generateDomain();

        // Create the ALEEnvironment and visualizer
        ALEEnvironment env = new ALEEnvironment(alePath, romPath, frameSkip, PoolingMethod.POOLING_METHOD_MAX);
        env.setRandomNoopMax(noopMax);
        ALEVisualExplorer exp = new ALEVisualExplorer(domain, env, ALEVisualizer.create());
        exp.initGUI();
        exp.startLiveStatePolling(1000/60);

        // Setup the ActionSet from the ALEDomain to use the ALEActions
        ActionSet actionSet = new ActionSet(domain);

        // Setup the training and test memory
        FrameExperienceMemory trainingExperienceMemory =
                new FrameExperienceMemory(experienceMemoryLength, maxHistoryLength, new ALEPreProcessor(), actionSet);
        // The size of the test memory is arbitrary but should be significantly greater than 1 to minimize copying
        FrameExperienceMemory testExperienceMemory =
                new FrameExperienceMemory(10000, maxHistoryLength, new ALEPreProcessor(), actionSet);


        // Initialize the DQN with the solver file.
        // NOTE: this Caffe architecture is made for 3 actions (the number of actions in Pong)
        DQN dqn = new DQN(solverFile, actionSet, trainingExperienceMemory, gamma);
        dqn.setRewardClip(rewardClip);
        dqn.setGradientClip(gradientClip);

        // Create the policies
        SolverDerivedPolicy learningPolicy =
                new AnnealedEpsilonGreedy(dqn, epsilonStart, epsilonEnd, epsilonAnnealDuration);
        SolverDerivedPolicy testPolicy = new EpsilonGreedy(dqn, testEpsilon);

        // Setup the learner
        DeepQLearner deepQLearner = new DeepQLearner(domain, gamma, replayStartSize, learningPolicy, dqn, trainingExperienceMemory);
        deepQLearner.setExperienceReplay(trainingExperienceMemory, dqn.batchSize);
        deepQLearner.useStaleTarget(staleUpdateFreq);
        deepQLearner.setUpdateFreq(updateFreq);

        // Setup the tester
        DeepQTester tester = new DeepQTester(testPolicy, testExperienceMemory, testExperienceMemory);

        // Setup helper
        TrainingHelper helper =
                new AtariDQN(deepQLearner, tester, dqn, actionSet, env, trainingExperienceMemory, testExperienceMemory);
        helper.setTotalTrainingSteps(totalTrainingSteps);
        helper.setTestInterval(testInterval);
        helper.setTotalTestSteps(totalTestSteps);
        helper.setMaxEpisodeSteps(maxEpisodeSteps);
        helper.enableSnapshots(snapshotPrefix, snapshotInterval);
        helper.recordResultsTo(resultsDirectory);
        //helper.verbose = true;

        // Uncomment this line to load learning state if resuming
        //helper.loadLearningState(snapshotDirectory);

        // Run helper
        helper.run();
    }
 
Example #26
Source File: LivePlayTest2.java    From oim-fx with MIT License 4 votes vote down vote up
/**
 * 转流器
 * 
 * @param inputFile
 * @param outputFile
 * @throws Exception
 * @throws org.bytedeco.javacv.FrameRecorder.Exception
 * @throws InterruptedException
 */
public static void recordPush(String inputFile, int v_rs) throws Exception, org.bytedeco.javacv.FrameRecorder.Exception, InterruptedException {
	Loader.load(opencv_objdetect.class);
	long startTime = 0;
	FrameGrabber grabber = FFmpegFrameGrabber.createDefault(inputFile);
	try {
		grabber.start();
	} catch (Exception e) {
		try {
			grabber.restart();
		} catch (Exception e1) {
			throw e;
		}
	}

	OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
	Frame grabframe = grabber.grab();
	IplImage grabbedImage = null;
	if (grabframe != null) {
		System.out.println("取到第一帧");
		grabbedImage = converter.convert(grabframe);
	} else {
		System.out.println("没有取到第一帧");
	}

	System.out.println("开始推流");
	CanvasFrame frame = new CanvasFrame("camera", CanvasFrame.getDefaultGamma() / grabber.getGamma());
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setAlwaysOnTop(true);
	while (frame.isVisible() && (grabframe = grabber.grab()) != null) {
		System.out.println("推流...");
		frame.showImage(grabframe);
		grabbedImage = converter.convert(grabframe);
		Frame rotatedFrame = converter.convert(grabbedImage);

		if (startTime == 0) {
			startTime = System.currentTimeMillis();
		}

		Thread.sleep(40);
	}
	frame.dispose();

	grabber.stop();
	System.exit(2);
}