Java调用Python问题

最近在做项目的时候,需要使用java调用python项目代码来实现图片模糊的判断功能。
于是便找了一些文章,使用了jython进行调用。
但是出现了一个问题,如果写一个简单的python文件,做一些计算、打印类的,可以进行正常运行,
但是一旦加载的是复杂的工具python项目,就会各种报错。

以下是pytho程序代码:

import sys
import argparse
import logging
import pathlib
import json

import cv2

from blur_detection import estimate_blur
from blur_detection import fix_image_size
from blur_detection import pretty_blur_map


def parse_args():
    parser = argparse.ArgumentParser(description='run blur detection on a single image')
    parser.add_argument('-i', '--images', type=str, nargs='+', required=True, help='directory of images')
    parser.add_argument('-s', '--save-path', type=str, default=None, help='path to save output')

    parser.add_argument('-t', '--threshold', type=float, default=100.0, help='blurry threshold')
    parser.add_argument('-f', '--variable-size', action='store_true', help='fix the image size')

    parser.add_argument('-v', '--verbose', action='store_true', help='set logging level to debug')
    parser.add_argument('-d', '--display', action='store_true', help='display images')

    return parser.parse_args()


def find_images(image_paths, img_extensions=['.jpg', '.png', '.jpeg', '.jfif']):
    img_extensions += [i.upper() for i in img_extensions]

    for path in image_paths:
        path = pathlib.Path(path)

        if path.is_file():
            if path.suffix not in img_extensions:
                logging.info(f'{path.suffix} is not an image extension! skipping {path}')
                continue
            else:
                yield path

        if path.is_dir():
            for img_ext in img_extensions:
                yield from path.rglob(f'*{img_ext}')


if __name__ == '__main__':
    assert sys.version_info >= (3, 6), sys.version_info
    args = parse_args()

    level = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(level=level)

    fix_size = not args.variable_size
    logging.info(f'fix_size: {fix_size}')

    if args.save_path is not None:
        save_path = pathlib.Path(args.save_path)
        assert save_path.suffix == '.json', save_path.suffix
    else:
        save_path = None

    results = []

    for image_path in find_images(args.images):
        image = cv2.imread(str(image_path))
        if image is None:
            logging.warning(f'warning! failed to read image from {image_path}; skipping!')
            continue

        logging.info(f'processing {image_path}')

        if fix_size:
            image = fix_image_size(image)
        else:
            logging.warning('not normalizing image size for consistent scoring!')

        blur_map, score, blurry = estimate_blur(image, threshold=args.threshold)

        logging.info(f'image_path: {image_path} score: {score} blurry: {blurry}')
        results.append({'input_path': str(image_path), 'score': score, 'blurry': blurry})

        if args.display:
            cv2.imshow('input', image)
            cv2.imshow('result', pretty_blur_map(blur_map))

            if cv2.waitKey(0) == ord('q'):
                logging.info('exiting...')
                exit()

    if save_path is not None:
        logging.info(f'saving json to {save_path}')

        with open(save_path, 'w') as result_file:
            data = {'images': args.images, 'threshold': args.threshold, 'fix_size': fix_size, 'results': results}
            json.dump(data, result_file, indent=4)


以下是调用python的java代码:

package com.opencns.common.util;

import org.python.util.PythonInterpreter;

import java.io.IOException;
import java.util.Properties;

public class PythonUtils {

    public static void main(String[] args) throws IOException {

        // 2. 面向对象式编程: 在Java中调用Python对象实例的方法
        Properties props = new Properties();
        props.put("python.home", "path to the Lib folder");
        props.put("python.console.encoding", "UTF-8");
        props.put("python.security.respectJavaAccessibility", "false");
        props.put("python.import.site", "false");
        Properties preprops = System.getProperties();
        PythonInterpreter.initialize(preprops, props, new String[0]);

        PythonInterpreter pi2 = new PythonInterpreter();

        // 加载python程序
        pi2.execfile("C:\\Users\\92446\\Desktop\\BlurDetection2\\process.py");
        pi2.exec("python process.py -i D:/1.png");

        pi2.cleanup();
        pi2.close();
    }

}

img

可以将Python获取的数据转成然后JAVA再进行请求。

【相关推荐】



  • 这篇博客: Java调用Python脚本:轻松实现两种语言的互操作性中的 使用Jython库在Java中执行Python脚本 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    Jython是一种允许在Java虚拟机中运行Python代码的解释器。 此解释器可以轻松地与Java集成,并且能够通过Python的标准库解析Python代码。 Jython提供了Python语言和Java平台之间的高度优化的互操作性,因此可以作为Java调用Python脚本的优先选择。

    以下是在Java中使用Jython库执行Python脚本的示例代码。

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("hello.py");
    

    Jython库提供了PythonInterpretter类,它可以充当Python解释器,并使Java可以执行Python代码。 例如,使用PythonInterpretter与Jython库,我们可以支持以下计算操作:

    interpreter.exec("x = 1+2+3");
    PyObject x = interpreter.get("x");
    System.out.println("x = " + x);
    

    在Java代码中,我们将简单的Pyhton计算传递给Python解释器。 运算的结果存储在变量“x”之中,并可以通过Java输出流和Python的print()函数打印出来。

    Jython库的优点是,它可以将Python代码和Java代码混合在一起。 在Java程序中,可以使用import语句导入Python模块,并使用Java本地类操作进行访问。借助Jython库,我们可以在Java中轻松访问Python模块,并快速获得我们需要的结果。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^