如何从字节数组生成python中的RGB图像?

如何从字节数组生成python中的RGB图像?,python,android,sockets,opencv,Python,Android,Sockets,Opencv,我正在做一个客户机/服务器应用程序。客户端是安卓设备,服务器是我运行python的PC。 在Android设备上,我拍摄了摄像头的预览,然后使用cameraX和analyze用例将其转换为字节数组: override fun analyze(image: ImageProxy?, rotationDegrees: Int) { val buffer = image?.planes?.get(0)?.buffer // Extract image data from callba

我正在做一个客户机/服务器应用程序。客户端是安卓设备,服务器是我运行python的PC。 在Android设备上,我拍摄了摄像头的预览,然后使用cameraX和analyze用例将其转换为字节数组:

override fun analyze(image: ImageProxy?, rotationDegrees: Int) {

    val buffer = image?.planes?.get(0)?.buffer
    // Extract image data from callback object
    val data = buffer?.toByteArray()
    // Convert the data into an array of pixel values
    // I commented this line, but I can use pixel value if you think is better
    //val pixels = data?.map { it.toInt() and 0xFF }
    Sender(mContext, mBufferedOutputStrem, mBufferedReader).execute(data)

}
private fun ByteBuffer.toByteArray(): ByteArray {
    rewind()    // Rewind the buffer to zero
    val data = ByteArray(remaining())
    get(data)   // Copy the buffer into a byte array
    return data // Return the byte array
}
然后,使用Sender类,我将包含图像的字节数组发送到服务器

override fun doInBackground(vararg p0: ByteArray): String {
    return try {

        mBufferedOutputStream.write(p0[0])
        mBufferedOutputStream.flush()
        ..........
在python服务器上,我使用以下行读取缓冲区:

buf = conn.recv(4096)
所以,buf是字节数组。如何将其转换为图像并保存到磁盘?我还想先用openCv显示图像。 我怎样才能做到这一点? ps.我应该传递另一个值而不是4096,而不是conn.recv4096吗?如果图像小于4096字节,我会遇到任何问题吗?

解决方案代码:

val buffer = ByteBuffer.allocate(1280 * 720 * 2)
        val yBuffer = image?.planes?.get(0)?.buffer // Y
        val uBuffer = image?.planes?.get(1)?.buffer // U
        val vBuffer = image?.planes?.get(2)?.buffer // V

        buffer.put(yBuffer!!)
        buffer.put(vBuffer!!)
        buffer.put(uBuffer!!)

        val data = buffer.toByteArray()

        val yuvImage = YuvImage(
            buffer.array(),
            ImageFormat.NV21, image.width, image.height, null
        )

        val out = ByteArrayOutputStream()
        yuvImage.compressToJpeg(
            Rect(
                0, 0,
                image.width, image.height
            ), 50, out
        )
        val imageBytes = out.toByteArray()
        val bm = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
        Sender(mContext, mBufferedOutputStrem, mBufferedReader).execute(imageBytes)
    }

}
private fun ByteBuffer.toByteArray(): ByteArray {
    rewind()    // Rewind the buffer to zero
    val data = ByteArray(remaining())
    get(data)   // Copy the buffer into a byte array
    return data // Return the byte array
}

目前还不清楚你们在发送方有什么样的图像。请从这个开始。接收器应该知道接收字节中的内容。所以我想知道怎么处理它。你为什么不发送一些文件呢?这样,接收器就不必知道字节中包含什么,只需将接收到的字节保存到文件中即可。发送前不能转换成jpg吗?关于4096。可能发送方发送的字节比这多。但没问题。你应该做一个循环,每次尝试读取4096字节,直到全部接收。我发现我需要读取所有三个平面,而不仅仅是位置为零的平面。然后使用android中的YuvImage,我成功地将图像转换为jpeg和字节数组。