androidscalingobject-detectioncamera-api

scale shape coordinates from custom view to adapt different screen sizes


I'm working on an app to detect objects in real time using the camera preview and then take a picture and display it in an other activity and a bounding box (most cases a polygon) will be drawn over the detected object.

I managed to do that and everything works fine. Now I'm trying to speed up the detection process by setting a small camera preview size and taking a picture with a bigger resolution by changing the camera parameters. But the coordinates that I will be getting must be scaled to match the big picture size.

In my case :

For the canvas size I'm using this to get the screen resolution :

public static int getScreenWidth() {
    return Resources.getSystem().getDisplayMetrics().widthPixels;
}

public static int getScreenHeight() {
    return Resources.getSystem().getDisplayMetrics().heightPixels;
}

my xml file looks like this :

<LinearLayout>
     ....
    <android.support.v7.widget.Toolbar
      ....
    </android.support.v7.widget.Toolbar>

      ....
    <FrameLayout
        android:id="@android:id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp">

        <packagename.CropImageView
            android:id="@+id/scannedImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:src="@mipmap/ic_launcher_round" />

    </FrameLayout>
</LinearLayout>

and in my custom view class CropImageView I'm passing four coordinates to the onDraw method and drawing paths between them.

Note : I saw a couple of questions about approximately the same subject but I couldn't relate to them since I couldn't a use case like mine. Any information, help is much appreciated.


Solution

  • all I needed to do is to find the scale factors for Y and X following this :

        scaleFactorY = (float) newWidth / oldWidth;
        scaleFactorX = (float) newHeight / oldHeight;
    

    then multiply the coordinates with those factors. Also you need to make sure that the preview size, picture size and the container that will hold the picture have the same aspect ratio or else you will get misplaced coordinates.

    to get the aspect ration you need simply need to do this : width / height.