use of org.bytedeco.javacpp.opencv_core.Mat in project javacv by bytedeco.
the class CaffeGooglenet method getMaxClass.
/* Find best class for the blob (i. e. class with maximal probability) */
public static void getMaxClass(Blob probBlob, Point classId, double[] classProb) {
// reshape the blob to 1x1000 matrix
Mat probMat = probBlob.matRefConst().reshape(1, 1);
minMaxLoc(probMat, null, classProb, null, classId, null);
}
use of org.bytedeco.javacpp.opencv_core.Mat in project javacv by bytedeco.
the class ImageSegmentation method main.
public static void main(String[] args) {
// Load the image
Mat src = imread(args[0]);
// Check if everything was fine
if (src.data().isNull())
return;
// Show source image
imshow("Source Image", src);
// Change the background from white to black, since that will help later to extract
// better results during the use of Distance Transform
UByteIndexer srcIndexer = src.createIndexer();
for (int x = 0; x < srcIndexer.rows(); x++) {
for (int y = 0; y < srcIndexer.cols(); y++) {
int[] values = new int[3];
srcIndexer.get(x, y, values);
if (Arrays.equals(values, WHITE)) {
srcIndexer.put(x, y, BLACK);
}
}
}
// Show output image
imshow("Black Background Image", src);
// Create a kernel that we will use for accuting/sharpening our image
Mat kernel = Mat.ones(3, 3, CV_32F).asMat();
FloatIndexer kernelIndexer = kernel.createIndexer();
// an approximation of second derivative, a quite strong kernel
kernelIndexer.put(1, 1, -8);
// do the laplacian filtering as it is
// well, we need to convert everything in something more deeper then CV_8U
// because the kernel has some negative values,
// and we can expect in general to have a Laplacian image with negative values
// BUT a 8bits unsigned int (the one we are working with) can contain values from 0 to 255
// so the possible negative number will be truncated
Mat imgLaplacian = new Mat();
// copy source image to another temporary one
Mat sharp = src;
filter2D(sharp, imgLaplacian, CV_32F, kernel);
src.convertTo(sharp, CV_32F);
Mat imgResult = subtract(sharp, imgLaplacian).asMat();
// convert back to 8bits gray scale
imgResult.convertTo(imgResult, CV_8UC3);
imgLaplacian.convertTo(imgLaplacian, CV_8UC3);
// imshow( "Laplace Filtered Image", imgLaplacian );
imshow("New Sharped Image", imgResult);
// copy back
src = imgResult;
// Create binary image from source image
Mat bw = new Mat();
cvtColor(src, bw, CV_BGR2GRAY);
threshold(bw, bw, 40, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
imshow("Binary Image", bw);
// Perform the distance transform algorithm
Mat dist = new Mat();
distanceTransform(bw, dist, CV_DIST_L2, 3);
// Normalize the distance image for range = {0.0, 1.0}
// so we can visualize and threshold it
normalize(dist, dist, 0, 1., NORM_MINMAX, -1, null);
imshow("Distance Transform Image", dist);
// Threshold to obtain the peaks
// This will be the markers for the foreground objects
threshold(dist, dist, .4, 1., CV_THRESH_BINARY);
// Dilate a bit the dist image
Mat kernel1 = Mat.ones(3, 3, CV_8UC1).asMat();
dilate(dist, dist, kernel1);
imshow("Peaks", dist);
// Create the CV_8U version of the distance image
// It is needed for findContours()
Mat dist_8u = new Mat();
dist.convertTo(dist_8u, CV_8U);
// Find total markers
MatVector contours = new MatVector();
findContours(dist_8u, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
// Create the marker image for the watershed algorithm
Mat markers = Mat.zeros(dist.size(), CV_32SC1).asMat();
// Draw the foreground markers
for (int i = 0; i < contours.size(); i++) drawContours(markers, contours, i, Scalar.all((i) + 1));
// Draw the background marker
circle(markers, new Point(5, 5), 3, RGB(255, 255, 255));
imshow("Markers", multiply(markers, 10000).asMat());
// Perform the watershed algorithm
watershed(src, markers);
Mat mark = Mat.zeros(markers.size(), CV_8UC1).asMat();
markers.convertTo(mark, CV_8UC1);
bitwise_not(mark, mark);
// imshow("Markers_v2", mark); // uncomment this if you want to see how the mark
// image looks like at that point
// Generate random colors
List<int[]> colors = new ArrayList<int[]>();
for (int i = 0; i < contours.size(); i++) {
int b = theRNG().uniform(0, 255);
int g = theRNG().uniform(0, 255);
int r = theRNG().uniform(0, 255);
int[] color = { b, g, r };
colors.add(color);
}
// Create the result image
Mat dst = Mat.zeros(markers.size(), CV_8UC3).asMat();
// Fill labeled objects with random colors
IntIndexer markersIndexer = markers.createIndexer();
UByteIndexer dstIndexer = dst.createIndexer();
for (int i = 0; i < markersIndexer.rows(); i++) {
for (int j = 0; j < markersIndexer.cols(); j++) {
int index = markersIndexer.get(i, j);
if (index > 0 && index <= contours.size())
dstIndexer.put(i, j, colors.get(index - 1));
else
dstIndexer.put(i, j, BLACK);
}
}
// Visualize the final image
imshow("Final Result", dst);
}
use of org.bytedeco.javacpp.opencv_core.Mat in project javacv by bytedeco.
the class OpenCVFaceRecognizer method main.
public static void main(String[] args) {
String trainingDir = args[0];
Mat testImage = imread(args[1], CV_LOAD_IMAGE_GRAYSCALE);
File root = new File(trainingDir);
FilenameFilter imgFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
name = name.toLowerCase();
return name.endsWith(".jpg") || name.endsWith(".pgm") || name.endsWith(".png");
}
};
File[] imageFiles = root.listFiles(imgFilter);
MatVector images = new MatVector(imageFiles.length);
Mat labels = new Mat(imageFiles.length, 1, CV_32SC1);
IntBuffer labelsBuf = labels.createBuffer();
int counter = 0;
for (File image : imageFiles) {
Mat img = imread(image.getAbsolutePath(), CV_LOAD_IMAGE_GRAYSCALE);
int label = Integer.parseInt(image.getName().split("\\-")[0]);
images.put(counter, img);
labelsBuf.put(counter, label);
counter++;
}
FaceRecognizer faceRecognizer = FisherFaceRecognizer.create();
// FaceRecognizer faceRecognizer = EigenFaceRecognizer.create();
// FaceRecognizer faceRecognizer = LBPHFaceRecognizer.create();
faceRecognizer.train(images, labels);
IntPointer label = new IntPointer(1);
DoublePointer confidence = new DoublePointer(1);
faceRecognizer.predict(testImage, label, confidence);
int predictedLabel = label.get(0);
System.out.println("Predicted label: " + predictedLabel);
}
use of org.bytedeco.javacpp.opencv_core.Mat in project javacv by bytedeco.
the class CaffeGooglenet method main.
public static void main(String[] args) throws Exception {
String modelTxt = "bvlc_googlenet.prototxt";
String modelBin = "bvlc_googlenet.caffemodel";
String imageFile = (args.length > 0) ? args[0] : "space_shuttle.jpg";
// ! [Create the importer of Caffe model]
Importer importer = null;
try {
// Try to import Caffe GoogleNet model
importer = createCaffeImporter(modelTxt, modelBin);
} catch (Exception e) {
// Importer can throw errors, we will catch them
e.printStackTrace();
}
if (importer == null) {
System.err.println("Can't load network by using the following files: ");
System.err.println("prototxt: " + modelTxt);
System.err.println("caffemodel: " + modelBin);
System.err.println("bvlc_googlenet.caffemodel can be downloaded here:");
System.err.println("http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel");
System.exit(-1);
}
// ! [Initialize network]
Net net = new Net();
importer.populateNet(net);
// We don't need importer anymore
importer.close();
// ! [Initialize network]
// ! [Prepare blob]
Mat img = imread(imageFile);
if (img.empty()) {
System.err.println("Can't read image from the file: " + imageFile);
System.exit(-1);
}
// GoogLeNet accepts only 224x224 RGB-images
resize(img, img, new Size(224, 224));
// Convert Mat to 4-dimensional dnn::Blob from image
Blob inputBlob = Blob.fromImages(img);
// ! [Prepare blob]
// ! [Set input blob]
// set the network input
net.setBlob(".data", inputBlob);
// ! [Set input blob]
// ! [Make forward pass]
// compute output
net.forward();
// ! [Make forward pass]
// ! [Gather output]
// gather output of "prob" layer
Blob prob = net.getBlob("prob");
Point classId = new Point();
double[] classProb = new double[1];
// find the best class
getMaxClass(prob, classId, classProb);
// ! [Gather output]
// ! [Print results]
List<String> classNames = readClassNames();
System.out.println("Best class: #" + classId.x() + " '" + classNames.get(classId.x()) + "'");
System.out.println("Best class: #" + classId.x());
System.out.println("Probability: " + classProb[0] * 100 + "%");
// ! [Print results]
}
Aggregations