jjzjj

java - 通过TCP将Opencv图像从Android发送到PC

coder 2023-09-18 原文

我正在开发一个抓取图像并将其发送到 PC 客户端进行显示的 Android 应用程序,Android 应用程序和 PC 应用程序都使用 Opencv。我要发送的图像是彩色图像(以 rbga 格式抓取)。

首先,我使用以下方法在 Java 应用程序中抓取图像:

InputImage = inputFrame.rgba();

接下来我使用 Mat 图像变量并使用以下 native (使用 JNI)函数将输入图像转换为字节数组:

    JNIEXPORT jbyteArray JNICALL Java_com_example_communicationmoduleTCPIP_communicationmoduleTCPIP_ConvertImageToByteArray(
        JNIEnv* Env, jobject,
        jlong addrInputImage){

    Mat& OutputImg = *(Mat*) addrInputImage;
    jbyteArray Array;

    //__android_log_write(ANDROID_LOG_ERROR, "Tag", "==== 1 ");

    // Init  java byte array
    Array = Env->NewByteArray(1536000);

    //__android_log_write(ANDROID_LOG_ERROR, "Tag", "==== 2 ");

    // Set byte array region with the size of the SendData CommStruct.
    // Now we can send the data back.
    Env->SetByteArrayRegion(Array, 0, 1536000, (jbyte*)OutputImg.data);

    //__android_log_write(ANDROID_LOG_ERROR, "Tag", "==== 3 ");

        return Array;
}

接下来是使用以下函数通过 TCP 结束字节数组(包含图像数据):

    // Send buffer, the method can be used by both client and server objects.
    public void SendByteBuffer(byte[] ByteBuffer){
    
    try {                         
        // Get socket output stream
        OutputStream OutputBuffer = ClientSocket.getOutputStream();
        
        //Write byte data to outputstream
        OutputBuffer.write(ByteBuffer);  
        
    } 
    catch (IOException e) {
        Log.e("TCPIPCommunicator: ", "Client: Failed to send", e);
        e.printStackTrace();
    }  
}

在 PC 端(在 C++ 中)我接收带有 boost lib 接收函数的缓冲区:

int CommunicationModuleTCPIPServer::RecieveBuffer(char Buffer[], int Size){

boost::asio::read(ServerSocket, boost::asio::buffer(TempBuffer, 1536000));
//boost::asio::read(ServerSocket, boost::asio::buffer((char*)InputImage, Size));
//cout <<"Temp buffer: " << TempBuffer << endl;


 int ptr=0;
 for (int i = 0;  i < InputImage.rows; i++) {
  for (int j = 0; j < InputImage.cols; j++) {
      InputImage.at<cv::Vec4b>(i,j) = cv::Vec4b(TempBuffer[ptr+ 0],TempBuffer[ptr+1],TempBuffer[ptr+2],TempBuffer[ptr+3]);
   ptr=ptr+3;
   }
  }

return COMMSUCCES;

然后我用opencv的imshow函数显示变量。问题是我没有在 pc 端的窗口中获取图像。我认为转换在某处出错了,但我看不到哪里。有人有想法吗?欢迎所有建议和反馈!

更新

我目前的代码如下:

在 PC 服务器端,我运行一个小程序来接收图像并尝试使用 imshow 显示它,它调用 RecieveImageBuffer 函数。在主函数下面。

int ImgReciever(){

    cout << "Setting up monitor server with ip: 192.168.2.11:5000" << endl;
    CommunicationModuleTCPIPServer TICM("192.168.2.11", 5000);
    //CommunicationModuleTCPIPServer TICM("192.168.1.103", 5000);

    VisionModule VM;

    TICM.RunServer();

    char ACK[10];

    ACK[0] = '@';

    while(1){
        cout << "Recieving data...." << endl;
        TICM.RecieveImageBuffer(TICM.TempBuffer, 384000);

        cout << "Data recieved, going to display image" << endl;

        imshow("Testwindow", TICM.InputImage);

        Sleep(1000);

        TICM.SendBuffer(ACK, 1);

    }

    return 0;
}

RecieveImageBuffer 函数(尝试切换行和列的形式,但随后程序崩溃)。读取函数总是在一次读取中接收 34800 个字节。并且 Tempbuffer 声明为:

uchar TempBuffer[384000]

int CommunicationModuleTCPIPServer::RecieveImageBuffer(uchar Buffer[], int Size){

    Mat Temp;
    int bytecount = 0;
    int bytecountTotal = 0;


    while(bytecountTotal < Size){
        bytecount = boost::asio::read(ServerSocket, boost::asio::buffer(Buffer, Size));
        cout << "Recieved chunck size: " << bytecount << endl;
        bytecountTotal = bytecountTotal + bytecount;
        bytecount = 0;

    }

    cout << "Recieved in total: " + bytecountTotal << endl;

     int ptr=0;
        for (int i = 0;  i < InputImage.rows; i++) {
            for (int j = 0; j < InputImage.cols; j++) {
          //InputImage.at<cv::Vec4b>(i,j) = cv::Vec4b(TempBuffer[ptr+ 0],TempBuffer[ptr+1],TempBuffer[ptr+2],TempBuffer[ptr+3]);
       //ptr=ptr+3;
          ptr++;
          InputImage.at<uchar>(i,j) = TempBuffer[ptr];

       }
      }

     return COMMSUCCES;
}

在 Android 端我发送图像,首先我抓取并转换灰度图像,缓冲区大小与 pc 缓冲区的大小匹配。

    OutputImage = inputFrame.gray();
long Size = (OutputImage.total() * OutputImage.channels());
      CMTCP.bufferByte = new byte[(int) Size];
            
CMTCP.bufferByte = ConvertMatToByteArray(OutputImage.getNativeObjAddr(), Size);

ConvertMatToByteArray 函数如下所示:

JNIEXPORT jbyteArray JNICALL Java_com_example_opencv1_MainActivity_ConvertMatToByteArray(
    JNIEnv* Env, jobject, jlong addrInputImage, jlong Size){

Mat& OutputImg = *(Mat*) addrInputImage;
jbyteArray Array;

// Init  java byte array
Array = Env->NewByteArray(Size);


// Set byte array region with the size of the SendData CommStruct.
// Now we can send the data back.
Env->SetByteArrayRegion(Array, 0, Size, (jbyte*)OutputImg.data);


    return Array;

TCP 客户端在一个线程中运行,该线程发送图像缓冲区,然后收到新发送的确认。

线程函数如下所示:

while(true){
        
        
        if(SendFrame){
            //System.out.println("Converting image");
            // Convert Buffer
            //ImgDataSend = ConvertImageToByteArray(InputImage.getNativeObjAddr(), 10, 20, 30);
            //System.out.println("Image converted");
            
            
            // Send new image buffer
            System.out.println("Sending frame data");
            SendByteBuffer(bufferByte);
            SendFrame = false;
            System.out.println("Image data send");
            
            
            // Wait for ACK 
            while(NoAck){
                RecieveBuffer();
                //System.out.println("Recieved: " +RecieveString);
                
                if(RecieveString == "@"){
                    System.out.println("GOT ACK");
                    bufferByte = new byte[384000];
                    NoAck = false;
                    RecieveString = "#";
                }
            }
        }

SendByteBuffer 函数如下所示:

    // Send buffer, the method can be used by both client and server objects.
public void SendByteBuffer(byte[] ByteBuffer){

    /*
    BufferedWriter out;
    try {
        out = new BufferedWriter(new OutputStreamWriter(ClientSocket.getOutputStream()));
        out.write(bufferByte.toString()); 
        out.flush();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 
    
    */

    try {                         
        // Get socket output stream
        OutputStream OutputBuffer = ClientSocket.getOutputStream();
        
        //Write byte data to outputstream
        OutputBuffer.write(bufferByte);  
        //OutputBuffer.flush();
        
    } 
    catch (IOException e) {
        Log.e("TCPIPCommunicator: ", "Client: Failed to send", e);
        e.printStackTrace();
    }  
}

我收到发送和确认功能消息,但显示图像的 PC 端窗口保持灰色并且没有响应(在标题栏中说)

最佳答案

我假设您已经验证通信交换工作正常,并且平台之间没有小/大端问题,即。发送一个小字节字符串并检查其在另一端是否完好无损。

此外,检查读取是否返回所有数据 - 您可能需要调用它直到所有数据都已收到,尤其是对于大字节缓冲区。

inputFrame.rgba() 返回一个 4 channel 图像 - 我认为你需要 ptr=ptr+4;

关于java - 通过TCP将Opencv图像从Android发送到PC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21135673/

有关java - 通过TCP将Opencv图像从Android发送到PC的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  5. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. ruby-on-rails - Enumerator.new 如何处理已通过的 block ? - 2

    我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m

  9. ruby - 寻找通过阅读代码确定编程语言的ruby gem? - 2

    几个月前,我读了一篇关于ruby​​gem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:

  10. 通过 MacPorts 的 RubyGems 是个好主意吗? - 2

    从MB升级到新的MBP后,Apple的迁移助手没有移动我的gem。我这次是通过macports安装ruby​​gems,希望在下次升级时避免这种情况。有什么我应该注意的陷阱吗? 最佳答案 如果你想把你的gems安装在你的主目录中(在传输过程中应该复制过来,作为一个附带的好处,会让你以你自己的身份运行geminstall,而不是root),将gemhome:键设置为您在~/.gemrc中的主目录中的路径. 关于通过MacPorts的RubyGems是个好主意吗?,我们在StackOverf

随机推荐