由于人脸检测器仅适用于 jpg 文件,如何才能使其适用于所有格式?我让用户从 SD 卡中选择任何图像,因此图像可以是任何格式。我使用本文中提到的解码文件方法来缩小图像: Android: Resize a large bitmap file to scaled output file
我的问题是:
我们可以在decodefile方法中添加一些方法来首先将图像转换为jpg吗?
将图像转换为 jpg 以便面部检测器类检测面部的最佳且有效的方法是什么?
到目前为止我的代码:
public FaceView(Context context) {
super(context);
File photo = new File(selectedImagePath);
sourceImage = decodeFile(photo);
picWidth = sourceImage.getWidth();
picHeight = sourceImage.getHeight();
sourceImage = Bitmap.createScaledBitmap (sourceImage, picWidth, picHeight, false);
arrayFaces = new FaceDetector( picWidth, picHeight, NUM_FACES );
arrayFaces.findFaces(sourceImage, getAllFaces);
for (int i = 0; i < getAllFaces.length; i++)
{
getFace = getAllFaces[i];
try {
PointF eyesMP = new PointF();
getFace.getMidPoint(eyesMP);
eyesDistance[i] = getFace.eyesDistance();
Log.d("1st eye distance", "" + getFace.eyesDistance());
eyesMidPts[i] = eyesMP;
}
catch (Exception e)
{
if (DEBUG) Log.e("Face", i + " is null");
}
}
}
解码方法:
private Bitmap decodeFile(File f){
Bitmap b = null;
int screenWidth = 0;
int screenHeight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
{
w.getDefaultDisplay().getSize(size);
screenWidth = size.x;
screenHeight = size.y;
}
else
{
Display d = w.getDefaultDisplay();
screenWidth = d.getWidth();
screenHeight = d.getHeight();
}
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try{
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
// was > IMAGE_MAX_SIZE for both i changed it****
int scale = 1;
if (o.outHeight > screenHeight || o.outWidth > screenWidth) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(screenHeight /
(double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return b;
}
最佳答案
在 decodeFile()
方法的末尾,您有一个位图。您可以轻松依靠 Android 将其转换为 JPEG,方法是使用
Bitmap.compress(Bitmap.CompressFormat format, int quality, OutputStream stream)
与Bitmap.compressFormat.JPEG
这里有更多信息:Conversion of bitmap into jpeg in android
您应该能够将其保存到文件,或压缩到内存中(也许使用ByteArrayOutputStream
?)
关于java - 使人脸检测器适用于任何文件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20248883/