Я хотел бы извлечь палец из androidx.camera.view.PreviewView в Android Java.
Я использую объект ImageAnalysis для запуска функции анализа() в ExecutorService.
В анализе() есть параметр «@NonNull ImageProxy image», из которого я получаю растровое изображение.
Это растровое изображение должно быть обработано.
Мне нужны права последовательность алгоритмов opencvs для извлечения пальца.
Моя проблема в моем коде заключается в том, что иногда сегментация пальца неправильная, потому что фон может иметь похожие цвета.Моя цель — нарисовать контур вокруг пальца в режиме реального времени (в виде наложения или в ImageView).
Когда я делаю фотографию, я бы хотел, чтобы сегментированный палец был без фона.< /p>
imageAnalysis.setAnalyzer(executorService, new ImageAnalysis.Analyzer() {
@Override
public void analyze(@NonNull ImageProxy image) {
Mat src = new Mat();
Utils.bitmapToMat(image.toBitmap(), src);
float zoomFactor = 1.5f;
// Calculate new dimensions after zoom
int newWidth = (int) (src.width() / zoomFactor);
int newHeight = (int) (src.height() / zoomFactor);
// Define ROI (Region of Interest) for zoom
Rect roi = calculateRoi(src.width(), src.height(), newWidth, newHeight);
// Crop the region of interest from the original image
src = new Mat(src, roi);
Mat hsv = new Mat();
Mat bgr = new Mat();
Mat blurredImage = new Mat();
if (src.channels() == 1) {
Imgproc.cvtColor(src, bgr, Imgproc.COLOR_GRAY2BGR);
} else if (src.channels() == 4) {
Imgproc.cvtColor(src, bgr, Imgproc.COLOR_RGBA2BGR);
}
// Apply Gaussian blur
Imgproc.GaussianBlur(src, blurredImage, new org.opencv.core.Size(5, 5), 0);
// Imgproc.blur(src, blurredImage, new org.opencv.core.Size(7, 7));
Mat normalized = new Mat();
Core.normalize(blurredImage, normalized, 0, 255, Core.NORM_MINMAX);
Imgproc.cvtColor(normalized, hsv, Imgproc.COLOR_RGB2HSV);
// Define the range of HSV values for skin tones
Scalar lowerSkin = new Scalar(0, 20, 70);
Scalar upperSkin = new Scalar(20, 255, 255);
// Threshold the image to select only skin pixels
Mat skinMask = new Mat();
Core.inRange(hsv, lowerSkin, upperSkin, skinMask);
// Apply the mask to the original image to show only the skin pixels
Mat skin = new Mat();
Core.bitwise_and(src, src, skin, skinMask);
Mat gray = new Mat();
Imgproc.cvtColor(skin, gray, Imgproc.COLOR_RGB2GRAY);
// Apply histogram equalization
Mat histEqualized = new Mat();
Imgproc.equalizeHist(gray, histEqualized);
// Binarize the image using Otsu's method
Mat binary = new Mat();
Imgproc.threshold(histEqualized, binary, 125, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
// Imgproc.adaptiveThreshold(gray, binary, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C,Imgproc.THRESH_BINARY_INV , 15, 1);
List contours = new ArrayList();
Mat hierarchy = new Mat();
Imgproc.findContours(binary, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Find the largest contour
double maxArea = 0;
MatOfPoint largestContour = null;
for (MatOfPoint contour : contours) {
double area = Imgproc.contourArea(contour);
if (area > maxArea) {
maxArea = area;
largestContour = contour;
}
}
// Create a mask for the largest contour
Mat contourMask = Mat.zeros(src.size(), CvType.CV_8UC1);
if (largestContour != null) {
Imgproc.drawContours(contourMask, Arrays.asList(largestContour), -1, new Scalar(255), Core.FILLED);
}
// Apply the contour mask to the original image
Mat result = new Mat();
Core.bitwise_and(src, src, result, contourMask);
// Draw the largest contour on the result image
if (largestContour != null) {
Imgproc.drawContours(result, Arrays.asList(largestContour), -1, new Scalar(255, 255, 255), 1);
}
// Convert back to Bitmap
Bitmap bitmap = Bitmap.createBitmap(result.cols(), result.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(result, bitmap);
final Bitmap pBitmap = rotateBitmap(bitmap,90);
// Create a mutable copy of the bitmap
runOnUiThread(new Runnable() {
@Override
public void run() {
overlayView.setImageBitmap(pBitmap);
}
});
image.close();
}
});
Подробнее здесь: https://stackoverflow.com/questions/787 ... ntour-arou
Извлечение пальца OpenCV из изображения/просмотр в реальном времени с камеры и рисование контура вокруг пальца ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение