【问题标题】:How to generate RGB image in python from bytes array?如何从字节数组在python中生成RGB图像?
【发布时间】:2020-02-08 02:54:26
【问题描述】:

我正在做一个客户端/服务器应用程序。客户端是Android设备,服务器是我运行python的PC。 在Android设备上,我拍摄了相机的预览,然后以这种方式将其转换为字节数组(使用cameraX和分析用例):

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 显示图像。 我怎样才能做到这一点? 附言。我应该传递另一个值而不是 4096,而不是 conn.recv(4096)?如果图像小于 4096 字节,我会遇到什么问题吗?

【问题讨论】:

  • 目前还不清楚您在发送方拥有什么样的图像。所以请从这里开始。并且接收者应该知道接收到的字节中有什么。所以要知道如何处理它。
  • 为什么不发送文件?这样,接收方不必知道字节中的内容,只需将接收到的字节保存到文件中即可。发送前不能转成jpg吗?
  • 关于 4096。可能发件人发送的字节数比这多。但没问题。您应该创建一个循环,每次都尝试读取 4096 字节 untit all received。
  • 我发现我需要阅读所有三个平面,而不仅仅是位置为零的那个。然后使用 android 中的 YuvImage,我成功地将图像转换为 jpeg 和字节数组。

标签: python android sockets opencv


【解决方案1】:

解决方案代码:

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
}

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 2020-06-09
    • 2021-01-13
    • 1970-01-01
    • 2013-12-28
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多