需要使用android中的相机捕获矩形视图内的图像

时间:2016-03-31 09:20:23

标签: android opencv android-camera

我在android中创建了一个文档扫描应用程序,在我的项目中使用OpenCV和Scan库进行裁剪,我在相机视图中使用drawrect创建了一个矩形,现在我需要仅捕获该矩形部分内的图像并显示它在另一项活动中。

相关图片:

enter image description here

2 个答案:

答案 0 :(得分:4)

对我来说,我将采取整个图像,然后裁剪。 你的问题:"我怎么知道图像的哪个部分在矩形部分内,然后只有我可以通过它,希望你理解"。我的答案是你可以使用整个图像尺寸和相机显示屏尺寸的相关性缩放。然后你就会知道要裁剪哪个矩形部分。

这是代码示例。 请注意,您需要填写一些代码才能将文件保存为jpg,并在裁剪后保存。

    // 1. Save your bitmap to file
    public class MyPictureCallback implements Camera.PictureCallback  {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        try {
            //mPictureFile is a file to save the captured image
            FileOutputStream fos = new FileOutputStream(mPictureFile);
            fos.write(data);
            fos.close();

        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        }
    }
    }

    // Somewhere in your code
    // 2.1 Load bitmap from your .jpg file              
    Bitmap bitmap = BitmapFactory.decodeFile(path+"/mPictureFile_name.jpg");

    // 2.2 Rotate the bitmap to be the same as display, if need.
    ... Add some bitmap rotate code

    // 2.3 Size of rotated bitmap
    int bitWidth = bitmap.getWidth();
    int bitHeight = bitmap.getHeight();

    // 3. Size of camera preview on screen  
    int preWidth = preview.getWidth();
    int preHeight = preview.getHeight();

    // 4. Scale it. 
    // Assume you draw Rect as "canvas.drawRect(60, 50, 210, 297, paint);" command
    int startx = 60 * bitWidth / preWidth;
    int starty = 50 * bitHeight / preHeight;
    int endx = 210 * bitWidth / preWidth;
    int endy = 297 * bitHeight / preHeight;

    // 5. Crop image
    Bitmap blueArea = Bitmap.createBitmap(bitmap, startx, starty, endx, endy);

    // 6. Save Crop bitmap to file

答案 1 :(得分:-1)

这对您有用:How to programmatically take a screenshot in Android?

确保在Bitmap.createBitmap(v1.getDrawingCache())中传递的视图(代码示例中的v1)是一个视图组,其中包含您想要发送到第二个活动的图像

编辑: 我不认为你的预期流程是可行的。据我所知,相机意图不会采用允许绘制这样一个矩形的参数(虽然我可能是错的)。

相反,我建议您拍照,然后使用此类库(https://github.com/ArthurHub/Android-Image-Cropper)进行编辑,或者按照上面的建议编程。