java调用python机器学习模型的坑

Java调用Python的4中方法

1在java类中直接执行python语句
2在java类中直接调用本地python脚本
3使用Runtime.getRuntime()执行python脚本文件(推荐)
4调用python脚本中的函数

下面我们介绍第三种方法

Runtime.getRuntime()

Java端

public static void main(String[] args) throws IOException, InterruptedException {
            String exe = "C:\\xxxxxx\\python.exe";//调用自己的python路径
            String command = "F:\\xxxxxxxx\\test.py";//要调用的python函数脚本
            String url="C:\\xxxxxxxx\\R-C.jpg";//传递的参数可以多个,python端取就可以
            String[] cmdArr = new String[] {exe, command,url};//将参数封装
            Process process = Runtime.getRuntime().exec(cmdArr);//采用Process调用
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));//用输入流读取
            String line = null;
            while ((line = in.readLine()) != null) {
                    System.out.println(line);//输出调用结果
            }
            in.close();
            process.waitFor();
    }

坑1

坑1:String exe 一定要是自己电脑的python路径,否则可能会解析出null。

Python端

这是自己写的第一个机器学习的人脸识别情绪的模型调用预测代码。

emotion_dict = {'生气': 0, '悲伤': 5, '中性': 4, '厌恶': 1, '惊讶': 6, '恐惧': 2, '高兴': 3}
# 载入图像
url = argv[1]//传递的第一个参数
image = face_recognition.load_image_file(url)
face_locations = face_recognition.face_locations(image)
top, right, bottom, left = face_locations[0]
face_image = image[top:bottom, left:right]
face_image = cv2.resize(face_image, (48, 48))
face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)
face_image = np.reshape(face_image, [1, face_image.shape[0], face_image.shape[1], 1])
model = load_model("F:\\xxxxxxx\\model_v6_23.hdf5")//调用模型
predicted_class = np.argmax(model.predict(face_image))
label_map = dict((v, k) for k, v in emotion_dict.items())
predicted_label = label_map[predicted_class]
# print(type(predicted_label))

print(predicted_label)

坑2

坑2:model的调用,不能采用相对路径,一定要是绝对路径,否则因为是java调用python,所以会找不到机器学习模型加载。

坑3

坑3:java调用python输出会出现中文乱码的情况

网上有许多解决方案,包括修改java端的编码为utf-8还有修改python端的编码为utf-8等但都不管用。

原因

这是因为python中print函数的机制问题。
他的默认编码格式是(‘zh_CN’, ‘cp936’),而cp36
就是编码GB2312。
知道问题所在后我们就可以解决了。

解决方案1(Java端修改)

我采用的是Process方式。因此需要在java端将输入流的字符编码设置成Gb2312

BufferedReader in =
 new BufferedReader(new InputStreamReader(process.getInputStream(),"gb2312");

解决方案2(python端修改)

如果调用方式不一样的话,就可以采用在python端修改,修改他的输出编码格式。
(在文件头添加)

import io
import sys

sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值