1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
| package org.example.util;
import org.bytedeco.ffmpeg.*; import org.bytedeco.ffmpeg.global.avcodec; import org.bytedeco.javacv.*; import org.bytedeco.javacv.Frame; import org.bytedeco.opencv.*; import org.opencv.core.*; import org.opencv.core.Point; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier;
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.io.*; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer;
public class VidUtil { static final String HAARCASCADES = "F:\\test\\vid\\haarcascade_frontalface_alt_tree.xml"; static CascadeClassifier cascade;
static { new opencv_java(); new ffmpeg(); cascade = new CascadeClassifier(HAARCASCADES); }
public static void getFrameMatByVideo(String vidPath, int interval, Consumer<Mat> doFunc, Consumer<Integer> indexFunc, Consumer<Integer> totalFunc) throws FrameGrabber.Exception { try(FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber(vidPath)) { fFmpegFrameGrabber.start(); int totalIndex = fFmpegFrameGrabber.getLengthInFrames(); if(totalFunc != null) { totalFunc.accept(totalIndex); } Frame frame; final OpenCVFrameConverter.ToOrgOpenCvCoreMat converter = new OpenCVFrameConverter.ToOrgOpenCvCoreMat(); for (int i = 0; i < totalIndex; i += interval) { if(indexFunc != null) { indexFunc.accept(i); } fFmpegFrameGrabber.setFrameNumber(i); frame = fFmpegFrameGrabber.grabImage(); doFunc.accept(converter.convert(frame)); } } }
public static void getFrameMatByVideo(String vidPath, int interval, Consumer<Mat> doFunc) throws FrameGrabber.Exception { getFrameMatByVideo(vidPath, interval, doFunc, null, null); }
public static void saveMatAsImg(String path, Mat mat) { Imgcodecs.imwrite(path, mat); }
public static Mat getMatFromImg(String path) { return Imgcodecs.imread(path); }
public static Mat copy(Mat from) { Mat to = new Mat(); from.copyTo(to); return to; }
public static MatOfRect faceDetect(Mat srcImage) { Mat grayImage = new Mat(); Imgproc.cvtColor(srcImage, grayImage, Imgproc.COLOR_BGR2GRAY); MatOfRect faceDetections = new MatOfRect(); cascade.detectMultiScale(grayImage, faceDetections); return faceDetections; }
public static Mat mobileMonitoring(Mat previousFrame, Mat currentFrame, Mat frame3) { Imgproc.cvtColor(previousFrame, previousFrame, Imgproc.COLOR_BGR2GRAY); Imgproc.cvtColor(currentFrame, currentFrame, Imgproc.COLOR_BGR2GRAY); Imgproc.cvtColor(frame3, frame3, Imgproc.COLOR_BGR2GRAY);
Mat difFrame = new Mat(), difFrame2 = new Mat(), difFrame3 = new Mat(), tempFrame = new Mat();
Core.absdiff(currentFrame, previousFrame, difFrame); Core.absdiff(previousFrame, frame3, difFrame2); Core.bitwise_and(difFrame, difFrame2, difFrame3);
Imgproc.threshold(difFrame3, tempFrame, 20, 255.0, Imgproc.THRESH_BINARY); Imgproc.dilate(tempFrame, tempFrame, new Mat()); Imgproc.erode(tempFrame, tempFrame, new Mat());
return tempFrame; }
public static boolean isMove(Mat previousFrame, Mat currentFrame, Mat frame3) { final ArrayList<MatOfPoint> list = new ArrayList<>(); Mat hierarchy = new Mat(); Mat moveMat = mobileMonitoring(previousFrame, currentFrame, frame3);
Imgproc.findContours(moveMat, list, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); for (MatOfPoint point : list) { final double contour = Imgproc.contourArea(point); if(contour > 1000) { return true; } } return false; }
public static void moveRectangle(Mat previousFrame, Mat currentFrame, Mat frame3, String path) { Mat baseFrame = new Mat(); currentFrame.copyTo(baseFrame); final ArrayList<MatOfPoint> list = new ArrayList<>(); Mat hierarchy = new Mat(); Mat moveMat = mobileMonitoring(previousFrame, currentFrame, frame3); Imgproc.findContours(moveMat, list, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); for (MatOfPoint point : list) { final MatOfPoint2f matOfPoint2f = new MatOfPoint2f(point.toArray()); final RotatedRect rotatedRect = Imgproc.minAreaRect(matOfPoint2f); final Rect rect = rotatedRect.boundingRect(); final double contour = Imgproc.contourArea(point); if(contour > 1000) { Imgproc.rectangle(baseFrame, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),new Scalar(0, 0, 255), 2); } } saveMatAsImg(path, baseFrame); }
public static Mat faceRectangle(Mat srcImage) { MatOfRect faceDetections = faceDetect(srcImage); Mat dstImage = new Mat(); srcImage.copyTo(dstImage); for (Rect rect : faceDetections.toArray()) { Imgproc.rectangle(dstImage, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),new Scalar(0, 0, 255), 2); } return dstImage; }
public static List<Mat> cutFace(Mat srcImage) { Rect[] rectArr = faceDetect(srcImage).toArray(); final LinkedList<Mat> res = new LinkedList<>(); if(rectArr.length > 0) { for (Rect rect : rectArr) { res.add(new Mat(srcImage, rect)); } } return res; }
public static Mat cutFirstFace(Mat srcImage) { Rect[] rectArr = faceDetect(srcImage).toArray(); if(rectArr.length > 0) { return new Mat(srcImage, rectArr[0]); } return null; }
public static int compareHistogram(Mat img1, Mat img2) { int retVal = 0; if (null != img1 && null != img2) { Mat hsvImg1 = new Mat(); Mat hsvImg2 = new Mat(); Imgproc.cvtColor(img1, hsvImg1, Imgproc.COLOR_BGR2HSV); Imgproc.cvtColor(img2, hsvImg2, Imgproc.COLOR_BGR2HSV); List<Mat> listImg1 = new ArrayList<Mat>(); List<Mat> listImg2 = new ArrayList<Mat>(); listImg1.add(hsvImg1); listImg2.add(hsvImg2); MatOfFloat ranges = new MatOfFloat(0, 255); MatOfInt histSize = new MatOfInt(50); MatOfInt channels = new MatOfInt(0); Mat histImg1 = new Mat(); Mat histImg2 = new Mat(); Imgproc.calcHist(listImg1, channels, new Mat(), histImg1, histSize, ranges); Imgproc.calcHist(listImg2, channels, new Mat(), histImg2, histSize, ranges); Core.normalize(histImg1, histImg1, 0, 1, Core.NORM_MINMAX, -1, new Mat()); Core.normalize(histImg2, histImg2, 0, 1, Core.NORM_MINMAX, -1, new Mat()); double result0, result1, result2, result3; result0 = Imgproc.compareHist(histImg1, histImg2, 0); result1 = Imgproc.compareHist(histImg1, histImg2, 1); result2 = Imgproc.compareHist(histImg1, histImg2, 2); result3 = Imgproc.compareHist(histImg1, histImg2, 3); int count = 0; if (result0 > 0.9) { count++; } if (result1 < 0.1) { count++; } if (result2 > 1.5) { count++; } if (result3 < 0.3) { count++; } if (count >= 3) { retVal = 1; } }
return retVal; }
public static BufferedImage Mat2BufImg (Mat matrix, String fileExtension) { MatOfByte mob = new MatOfByte(); Imgcodecs.imencode(fileExtension, matrix, mob); byte[] byteArray = mob.toArray(); BufferedImage bufImage = null; try { InputStream in = new ByteArrayInputStream(byteArray); bufImage = ImageIO.read(in); } catch (Exception e) { e.printStackTrace(); } return bufImage; }
public static Mat BufImg2Mat (BufferedImage original, int imgType, int matType) { if (original == null) { throw new IllegalArgumentException("original == null"); } if (original.getType() != imgType) { BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), imgType); Graphics2D g = image.createGraphics(); try { g.setComposite(AlphaComposite.Src); g.drawImage(original, 0, 0, null); } finally { g.dispose(); } } byte[] pixels = ((DataBufferByte) original.getRaster().getDataBuffer()).getData(); Mat mat = Mat.eye(original.getHeight(), original.getWidth(), matType); mat.put(0, 0, pixels); return mat; }
public static void main(String[] args) { VidUtil util = new VidUtil(); util.getMove("F:\\test\\vid\\2.mp4", "F:\\test\\vid\\img\\res.flv");
}
private void getMove(String vidPath, String outputFile) { try(FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber(vidPath)) { fFmpegFrameGrabber.start();
FrameRecorder recorder = FrameRecorder.createDefault(outputFile, fFmpegFrameGrabber.getImageWidth(), fFmpegFrameGrabber.getImageHeight()); recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); recorder.setFormat("flv"); recorder.setFrameRate(fFmpegFrameGrabber.getFrameRate()); recorder.start();
final OpenCVFrameConverter.ToOrgOpenCvCoreMat converter = new OpenCVFrameConverter.ToOrgOpenCvCoreMat(); Mat frame1 = null, frame2 = null; final int total = fFmpegFrameGrabber.getLengthInFrames(); for (int i = 0; i < total; i++) { System.out.println(i + "/" + total); Frame frame = fFmpegFrameGrabber.grab(); Mat mat = converter.convert(frame);
if(frame1 == null) { frame1 = new Mat(); mat.copyTo(frame1); } else if(frame2 == null) { frame2 = new Mat(); mat.copyTo(frame2); } else { Mat f1 = new Mat(), f2 = new Mat(), f3 = new Mat(); frame1.copyTo(f1); frame2.copyTo(f2); mat.copyTo(f3); boolean move = VidUtil.isMove(f1, f2, f3); if(move) { recorder.record(frame); } frame2.copyTo(frame1); mat.copyTo(frame2); } } recorder.stop(); recorder.release(); fFmpegFrameGrabber.stop(); fFmpegFrameGrabber.release(); } catch (Exception e) { e.printStackTrace(); } }
public static void recordCamera(String outputFile, double frameRate)throws Exception { Loader.load(opencv_objdetect.class); FrameGrabber grabber = FrameGrabber.createDefault(0); grabber.start();
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage(); IplImage grabbedImage = converter.convert(grabber.grab()); int width = grabbedImage.width(); int height = grabbedImage.height();
FrameRecorder recorder = FrameRecorder.createDefault(outputFile, width, height); recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); recorder.setFormat("flv"); recorder.setFrameRate(frameRate);
recorder.start(); long startTime=0; long videoTS=0; CanvasFrame frame = new CanvasFrame("camera", CanvasFrame.getDefaultGamma() / grabber.getGamma()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setAlwaysOnTop(true); Frame rotatedFrame=converter.convert(grabbedImage); while (frame.isVisible() && (grabbedImage = converter.convert(grabber.grab())) != null) { rotatedFrame = converter.convert(grabbedImage); frame.showImage(rotatedFrame); if (startTime == 0) { startTime = System.currentTimeMillis(); } videoTS = 1000 * (System.currentTimeMillis() - startTime); recorder.setTimestamp(videoTS); recorder.record(rotatedFrame); Thread.sleep(40); } frame.dispose(); recorder.stop(); recorder.release(); grabber.stop(); } }
|