package ru.sfedu.opencvgraphic.api;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Locale;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import nu.pattern.OpenCV;
import org.apache.log4j.Logger;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.photo.Photo;
import ru.sfedu.opencvgraphic.Constant;
import ru.sfedu.opencvgraphic.OpenCVMain;
import ru.sfedu.opencvgraphic.models.OSType;
import ru.sfedu.opencvgraphic.utils.ConfigurationUtil;
public class MyAPI {
private static Logger logger = Logger.getLogger(MyAPI.class);
public OSType getOperatingSystemType() {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.contains("mac")) || (OS.contains("darwin"))) {
return OSType.MACOS;
} else if (OS.contains("win")) {
return OSType.WINDOWS;
} else if (OS.contains("nux")) {
return OSType.LINUX;
} else {
return OSType.OTHERS;
}
}
public void initApi() throws Exception {
switch (getOperatingSystemType()) {
case LINUX:
// System.load(ConfigurationUtil.getConfigurationEntry(Constant.PATH_TO_NATIVE_LIB_LINUX));
break;
case WINDOWS:
// System.load(ConfigurationUtil.getConfigurationEntry(Constant.PATH_TO_NATIVE_LIB_WINDOWS));
break;
case MACOS:
// System.load(ConfigurationUtil.getConfigurationEntry(Constant.PATH_TO_NATIVE_LIB_MACOS));
OpenCV.loadLocally();
break;
case OTHERS:
throw new Exception("Current OS does not support!!!!!");
default:
throw new Exception("Your OS does not support!!!");
}
}
public String changeChanel(int numChn, String srcImgName) throws IOException{
String dir = ConfigurationUtil.getConfigurationEntry(Constant.DIR_PATH);
String destDirPath = ConfigurationUtil.getConfigurationEntry(Constant.DIR_CHANGECHANEL);
Mat srcImage = Imgcodecs.imread(dir + srcImgName);
int numberChannels = srcImage.channels();
logger.info(numberChannels);
// showImage(srcImage);
int totalBytes = (int) (srcImage.total() * srcImage.elemSize());
byte buffer[] = new byte[totalBytes];
srcImage.get(0, 0, buffer);
for (int i = 0; i < totalBytes; i++) {
if (i % numberChannels + 1 == numChn) {
buffer[i] = 0;
}
}
srcImage.put(0, 0, buffer);
// showImage(srcImage);
Imgcodecs.imwrite(destDirPath + "changeChanel.png", srcImage);
return destDirPath + "changeChanel.png";
}
public void showImage(Mat m){
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels()*m.cols()*m.rows();
byte [] b = new byte[bufferSize];
m.get(0,0,b);
BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
ImageIcon icon=new ImageIcon(image);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(image.getWidth(null)+50, image.getHeight(null)+50);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public String morfologyTest(String fileName) throws Exception{
String destDirPath = ConfigurationUtil.getConfigurationEntry(Constant.DIR_MORFOLOGYTEST);
String dir = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
Mat src = Imgcodecs.imread(dir + fileName, Imgcodecs.IMREAD_COLOR);
try {
String prfName = "mrf_";
Mat dst = src.clone();
Mat element_10 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(10, 10));
Mat element_01 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(1, 1));
Mat element_05 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 5));
Imgproc.erode(src, dst, element_10);
Imgcodecs.imwrite(destDirPath + prfName + "erode_10_" + fileName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_01);
Imgcodecs.imwrite(destDirPath + prfName + "erode_01_" + fileName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_05);
Imgcodecs.imwrite(destDirPath + prfName + "erode_05_" + fileName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.dilate(src, dst, element_10);
Imgcodecs.imwrite(destDirPath + prfName + "dilate_10_" + fileName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.dilate(src, dst, element_01);
Imgcodecs.imwrite(destDirPath + prfName + "dilate_01_" + fileName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.dilate(src, dst, element_05);
Imgcodecs.imwrite(destDirPath + prfName + "dilate_05_" + fileName, dst);
// showImage(dst);
} catch (Exception ex) {
System.err.println(Arrays.toString(ex.getStackTrace()));
}
return destDirPath;
}
public String filtering_core(String imgPath) throws Exception{
String destDirPath = ConfigurationUtil.getConfigurationEntry(Constant.DIR_FILTERINGCORE);
String dir = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
try {
String prfName = "mrf_";
Mat src = Imgcodecs.imread(dir + imgPath, Imgcodecs.IMREAD_COLOR);
Mat dst = src.clone();
Mat element_303 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 3));
Mat element_505 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 5));
Mat element_707 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(7, 7));
Mat element_909 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(9, 9));
Mat element_13013 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(13, 13));
Mat element_15015 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(15, 15));
Imgproc.erode(src, dst, element_303);
Imgcodecs.imwrite(destDirPath + prfName + "rec_303_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_505);
Imgcodecs.imwrite(destDirPath + prfName + "rec_505_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_707);
Imgcodecs.imwrite(destDirPath + prfName + "rec_707_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_909);
Imgcodecs.imwrite(destDirPath + prfName + "rec_909_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_13013);
Imgcodecs.imwrite(destDirPath + prfName + "rec_13013_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_15015);
Imgcodecs.imwrite(destDirPath + prfName + "rec_15015_" + imgPath, dst);
// showImage(dst);
element_303 = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(3, 3));
element_505 = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(5, 5));
element_707 = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(7, 7));
element_909 = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(9, 9));
element_13013 = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(13, 13));
element_15015 = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(15, 15));
Imgproc.erode(src, dst, element_303);
Imgcodecs.imwrite(destDirPath + prfName + "cr_303_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_505);
Imgcodecs.imwrite(destDirPath + prfName + "cr_505_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_707);
Imgcodecs.imwrite(destDirPath + prfName + "cr_707_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_909);
Imgcodecs.imwrite(destDirPath + prfName + "cr_909_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_13013);
Imgcodecs.imwrite(destDirPath + prfName + "cr_13013_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_15015);
Imgcodecs.imwrite(destDirPath + prfName + "cr_15015_" + imgPath, dst);
// showImage(dst);
element_303 = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3));
element_505 = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
element_707 = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(7, 7));
element_909 = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(9, 9));
element_13013 = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(13, 13));
element_15015 = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(15, 15));
Imgproc.erode(src, dst, element_303);
Imgcodecs.imwrite(destDirPath + prfName + "ell_303_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_505);
Imgcodecs.imwrite(destDirPath + prfName + "ell_505_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_707);
Imgcodecs.imwrite(destDirPath + prfName + "ell_707_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_909);
Imgcodecs.imwrite(destDirPath + prfName + "ell_909_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_13013);
Imgcodecs.imwrite(destDirPath + prfName + "ell_13013_" + imgPath, dst);
// showImage(dst);
dst = src.clone();
Imgproc.erode(src, dst, element_15015);
Imgcodecs.imwrite(destDirPath + prfName + "ell_15015_" + imgPath, dst);
// showImage(dst);
} catch (Exception ex) {
System.err.println(Arrays.toString(ex.getStackTrace()));
}
return destDirPath;
}
public String filtering(String imgName, Size coreSize) throws Exception{
String destDirPath = ConfigurationUtil.getConfigurationEntry(Constant.DIR_FILTERING);
String dir = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
try {
String prfName = "mrf_";
Mat src = Imgcodecs.imread(dir + imgName, Imgcodecs.IMREAD_COLOR);
Mat dst = src.clone();
Imgproc.blur(src, dst, coreSize);
Imgcodecs.imwrite(destDirPath + prfName + "blur_selected_" + imgName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.GaussianBlur(src, dst, coreSize, 0, 1.0);
Imgcodecs.imwrite(destDirPath + prfName + "gausBlur_" + imgName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.medianBlur(src, dst, (int)(coreSize.height));
Imgcodecs.imwrite(destDirPath + prfName + "mediaBlur_" + imgName, dst);
// showImage(dst);
dst = src.clone();
Imgproc.bilateralFilter(src, dst, -1, 100.0, 1.0);
Imgcodecs.imwrite(destDirPath + prfName + "bilatBlur_" + imgName, dst);
// showImage(dst);
} catch (Exception ex) {
System.err.println(Arrays.toString(ex.getStackTrace()));
}
return destDirPath;
}
public String fillFlood(String srcImgName, Point seedPoint, Scalar color, Scalar loDiff, Scalar upDiff) throws IOException{
String dirPath = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
String destDirPath = ConfigurationUtil.getConfigurationEntry(Constant.DIR_FILLFLOOD);
Mat srcImage = Imgcodecs.imread(dirPath + srcImgName);
if (color == null) {
Double r = Math.random() * 255;
Double g = Math.random() * 255;
Double b = Math.random() * 255;
color = new Scalar(b, g, r);
}
Mat mask = new Mat();
// showImage(srcImage);
Imgproc.floodFill(srcImage, mask, seedPoint, color, new Rect(), loDiff, upDiff, Imgproc.FLOODFILL_FIXED_RANGE);
Imgcodecs.imwrite(destDirPath + "fillFloud.png", srcImage);
// showImage(srcImage);
return destDirPath + "fillFloud.png";
}
public void fillPyramids() throws Exception{
String srcImgName = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
Mat srcImage = Imgcodecs.imread(srcImgName);
Mat mask = new Mat();
// showImage(srcImage);
Imgproc.pyrDown(srcImage, mask);
// showImage(mask);
Imgproc.pyrUp(mask, mask);
// showImage(mask);
Core.subtract(srcImage, mask, mask);
// showImage(mask);
}
public Mat upDownPyramids(Mat image) {
Mat mask = new Mat();
Imgproc.pyrDown(image, mask);
Imgproc.pyrUp(mask, mask);
return mask;
}
public String pyramidUp(
String srcImgName,
int iterations
) throws Exception{
String dirPath = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
String destDirPath = ConfigurationUtil.getConfigurationEntry(Constant.DIR_PYRAMIDUP);
Mat srcImage = Imgcodecs.imread(dirPath + srcImgName);
Mat mask = new Mat();
Imgproc.pyrUp(srcImage, mask);
for (int i = 1; i < iterations; i++) {
Imgproc.pyrUp(mask, mask);
}
Imgcodecs.imwrite(destDirPath + iterations + "pyramidUpImage.jpg", mask);
return destDirPath + iterations + "pyramidUpImage.jpg";
}
public String pyramidDown (
String srcImgName,
int iterations
) throws Exception{
String dirPath = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
String destDirPath = ConfigurationUtil.getConfigurationEntry(Constant.DIR_PYRAMIDDOWN);
Mat srcImage = Imgcodecs.imread(dirPath + srcImgName);
Mat mask = new Mat();
Imgproc.pyrDown(srcImage, mask);
for (int i = 1; i < iterations; i++) {
Imgproc.pyrDown(mask, mask);
}
Imgcodecs.imwrite(destDirPath + iterations + "pyramidDownImage.jpg", mask);
return destDirPath + iterations + "pyramidDownImage.jpg";
}
public String upDownPyramids(String imgName, int iterations) throws Exception{
String dir = ConfigurationUtil.getConfigurationEntry(Constant.DIR_UPDOWNPYRAMIDS);
String srcImgName = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH) + imgName;
Mat srcImage = Imgcodecs.imread(srcImgName);
Mat mask = srcImage;
for (int i = 0; i < iterations; i++) {
mask = MyAPI.this.upDownPyramids(mask);
// showImage(mask);
}
Core.subtract(srcImage, mask, mask);
Imgcodecs.imwrite(dir + iterations +"upDown.png", mask);
// showImage(mask);
return dir + iterations +"upDown.png";
}
public String segment(String name,
double minWidth,
double minHeight,
double maxWidth,
double maxHeight
) throws Exception{
ArrayList<Mat> findedRects = new ArrayList<Mat>();
String srcImgName = ConfigurationUtil.getConfigurationEntry(Constant.DIR_SEGMENT);
String dir = ConfigurationUtil.getConfigurationEntry(Constant.IMG_PATH);
Mat src = Imgcodecs.imread(dir + name, Imgcodecs.IMREAD_COLOR);
Mat dst = src.clone();
Imgcodecs.imwrite(srcImgName + "first.png", dst);
// showImage(dst);
// 1
Mat grayImage = new Mat();
Imgproc.cvtColor(dst, grayImage, Imgproc.COLOR_BGR2GRAY);
Imgcodecs.imwrite(srcImgName + "0.png", grayImage);
// 2
Mat denoisingImage = new Mat();
Photo.fastNlMeansDenoising(grayImage, denoisingImage);
Imgcodecs.imwrite(srcImgName + "1.png", denoisingImage);
// 3
Mat histogramEqualizationImage = new Mat();
Imgproc.equalizeHist(denoisingImage, histogramEqualizationImage);
Imgcodecs.imwrite(srcImgName + "2.png", histogramEqualizationImage);
// 4
Mat morphologicalOpeningImage = new Mat();
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 5));
Imgproc.morphologyEx(histogramEqualizationImage, morphologicalOpeningImage,
Imgproc.MORPH_RECT, kernel);
Imgcodecs.imwrite(srcImgName + "3.png", morphologicalOpeningImage);
// 5
Mat subtractImage = new Mat();
Core.subtract(histogramEqualizationImage, morphologicalOpeningImage, subtractImage);
Imgcodecs.imwrite(srcImgName + "4.png", subtractImage);
// 6
Mat thresholdImage = new Mat();
double threshold = Imgproc.threshold(subtractImage, thresholdImage, 50, 255,
Imgproc.THRESH_OTSU);
Imgcodecs.imwrite(srcImgName + "5.png", thresholdImage);
thresholdImage.convertTo(thresholdImage, CvType.CV_16SC1);
// 7
Mat edgeImage = new Mat();
thresholdImage.convertTo(thresholdImage, CvType.CV_8U);
// showImage(thresholdImage);
Imgproc.Canny(thresholdImage, edgeImage, threshold, threshold * 3, 3, true);
Imgcodecs.imwrite(srcImgName + "6.png", edgeImage);
// 8
Mat dilatedImage = new Mat();
Imgproc.dilate(thresholdImage, dilatedImage, kernel);
Imgcodecs.imwrite(srcImgName + "7.png", dilatedImage);
// 9
ArrayList<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(dilatedImage, contours, new Mat(), Imgproc.RETR_TREE,
Imgproc.CHAIN_APPROX_SIMPLE);
contours.sort(Collections.reverseOrder(Comparator.comparing(Imgproc::contourArea)));
int iterator = 1;
for (MatOfPoint contour : contours.subList(0, 10)) {
System.out.println(Imgproc.contourArea(contour));
MatOfPoint2f point2f = new MatOfPoint2f();
MatOfPoint2f approxContour2f = new MatOfPoint2f();
MatOfPoint approxContour = new MatOfPoint();
contour.convertTo(point2f, CvType.CV_32FC2);
double arcLength = Imgproc.arcLength(point2f, true);
Imgproc.approxPolyDP(point2f, approxContour2f, 0.03 * arcLength, true);
approxContour2f.convertTo(approxContour, CvType.CV_32S);
Rect rect = Imgproc.boundingRect(approxContour);
if (rect.width > minWidth && rect.width < maxWidth &&
rect.height > minHeight && rect.height < maxHeight) {
double ratio = (double)rect.height / rect.width;
Mat submat = src.submat(rect);
Imgproc.resize(submat, submat, new Size(400, 400 * ratio));
// showImage(submat);
Imgcodecs.imwrite(srcImgName + iterator + "segm.png", submat);
iterator++;
findedRects.add(submat);
}
}
return srcImgName;
}
}