从Python向Android发送JSON格式的OpenCV图像

2024-10-01 15:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python服务器,它使用OpenCV对图像进行操作。之后,我想通过先前打开的socketserver将结果图像发送到Android设备。对于图像,我还想发送一个字符串,因此我构建了一个要发送的JSON对象。Android应用程序接收的对象包含这两个元素,但图像是OpenCVMat对象的字符串表示。 我找不到任何方法来转换byte数组中图像的这种表示,以便在Android应用程序中重建图像并显示它。在

如何正确发送图像,然后在Android应用程序中转换?在

下面是我的Python脚本,用于构建图像、JSON并发送它:

imgou = numpy.zeros((numpy.size(mat_image, 0), numpy.size(mat_image, 1), 3), numpy.uint8)
cv2.drawContours(imgou, cont, idx, (0,255,0), 3)

print "build json"
outjson = {}
outjson['img'] = numpy.array_str(imgou)
outjson['leaf'] = leaf
json_data = json.dumps(outjson)

self.request.sendall(json_data)

以下是Android应用程序处理JSON的代码:

^{pr2}$

此时,我应该在mat_img中有Mat对象,可以写入文件并显示出来。在


Tags: 对象字符串图像imagenumpyjson应用程序img
2条回答

基于answer of Avinash,我设法将图像打包到一个JSON对象中,然后从Android应用程序中检索它。由于OpenCV提供了一种Bitmap到{}转换的方法,因此发送图像而不是{}对象更方便。在

下面是Python服务器的工作代码:

img_file = open("image1.png", "r")

# read the image file
data = img_file.read()        

# build JSON object
outjson = {}
outjson['img'] = data.encode('base64')   # data has to be encoded base64 and decode back in the Android app base64 as well
outjson['leaf'] = "leaf"
json_data = json.dumps(outjson)

# close file pointer and send data
img_file.close()
self.request.sendall(json_data)

以下是Android应用程序的工作代码:

^{pr2}$

干杯!在

从您的服务器可以将图像发送到字节数组中 现在在你的android应用程序中,你可以接收字节数组并将其转换成位图,然后转换成Mat

byte[] bitmapdata = Base64.decode("your byte string", Base64.DEFAULT);
//here the data coming from server is assumed in Base64
//if you are sending bytes in plain string you can directly convert it to byte array
    Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0,        bitmapdata.length);

//android OpenCv function
org.opencv.android.Utils.bitmapToMat(bitmap,mat);

相关问题 更多 >

    热门问题