在我的项目中,我想从实时摄像头源中选择一个对象,然后只为所选区域创建一个 JPEG 文件。所以在 onCameraFrame 方法中,我在 Imgproc.drawContours(mRgba, contours, 0, CONTOUR_COLOR);
中设置参数 0 以选择第一个项目,即所选项目。然后我尝试为该项目实现一个绑定(bind)矩形。
OnCameraFrame()
public Mat onCameraFrame(CvCameraViewFrame inputFrame) { mRgba = inputFrame.rgba();
if (mIsColorSelected) {
mDetector.process(mRgba);
List<MatOfPoint> contours = mDetector.getContours();
Log.e(TAG, "Contours count: " + contours.size());
Imgproc.drawContours(mRgba, contours, 0, CONTOUR_COLOR);
Mat colorLabel = mRgba.submat(4, 68, 4, 68);
colorLabel.setTo(mBlobColorRgba);
MatOfPoint2f contour2f = new MatOfPoint2f( contours.get(0).toArray());
//Processing on mMOP2f1 which is in type MatOfPoint2f
double approxDistance = Imgproc.arcLength(contour2f, true)*0.02;
Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true);
//Convert back to MatOfPoint
MatOfPoint points = new MatOfPoint( approxCurve.toArray() );
// Get bounding rect of contour
Rect rect = Imgproc.boundingRect(points);
Mat selectedRegion = mRgba.submat(rect);
Bitmap bmp = null;
try {
bmp = Bitmap.createBitmap(selectedRegion.cols(), selectedRegion.rows(), Bitmap.Config.ARGB_8888);
convertBitmapToImage(bmp);
} catch (CvException e) {
Log.d("Exception", e.getMessage());
}
}
return mRgba;
}
然后将mat对象转换为位图并保存为JPEG格式
转换位图到图像
private void convertBitmapToImage(Bitmap bmp) {
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/Dummy");
if (!root.exists()) {
root.mkdirs();
} else {
System.out.print("Exists");
}
File f = new File(root, "filename.jpeg");
//Convert bitmap to byte array
Bitmap bitmap = bmp;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos);
byte[] bitmapdata = bos.toByteArray();
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//write the bytes in file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
但是它创建了一个空白的 JPEG 文件
我做错了什么或需要做什么
最佳答案
我没有检查您的代码,但我认为问题出在您的 bmp 上。 你应该这样使用:
Bitmap bmp = Bitmap.createBitmap(src.cols(), src.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(src, bmp);
在您的 convertBitmapToImage 方法之前。 src 是您要保存为图像文件的 Mat 对象。
关于android - 如何从opencv android中的选定轮廓裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33772503/