![](/img/trans.png)
[英]OpenCV: How to save detected face to SD Card location in android?
[英]How to save detected face in Android using OpenCV?
我正在使用OpenCV的示例代碼來檢測android設備的人臉。 我只想將檢測到的面部區域保存到SD卡中。 我正在嘗試將mat轉換為Bitmap並保存。 但是我的問題是,它保存了整個圖像,而不僅僅是面部。 這是我將mat轉換為位圖的方法
Bitmap bitmap = Bitmap.createBitmap(mGray.cols(), mGray.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mGray, bitmap);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
我是Opencv的初學者。 請幫忙。 先感謝您
問題是,您永遠不會嘗試獲得面部像素。 檢測到臉部之后,建議您執行以下操作:
Mat mFaceMatrix = mRgba.submat(facesArray.y, facesArray.y + facesArray.heigth, facesArray.x, facesArray.x + facesArray.width);
現在將此矩陣傳遞給createBitmap函數應該可以解決問題。
Bitmap bitmap = Bitmap.createBitmap(mFaceMatrix.cols(), mFaceMatrix.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mFaceMatrix, bitmap);
您的代碼看起來不錯。 我認為問題出在您的矩陣mGray。 mGray似乎包含整個圖像像素,並且您正在使用它來創建位圖。 因此,我的建議是先檢查您的mGray矩陣並獲取面部區域,然后將像素復制到另一個矩陣,然后使用僅包含面部的新矩陣創建位圖。 希望能幫助到你。
假設只有一張臉。 我們可以裁剪面部檢測的結果,並按照以下python腳本中的描述進行保存:
import cv2
import sys
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if cv2.waitKey(1) & 0xFF == ord('c'):
crop = frame[y: y + h, x: x + w]
cv2.imwrite("face.jpg", crop)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.