Example usage for org.opencv.core Mat rows

List of usage examples for org.opencv.core Mat rows

Introduction

In this page you can find the example usage for org.opencv.core Mat rows.

Prototype

public int rows() 

Source Link

Usage

From source file:edu.sust.cse.analysis.news.NewsAnalysis.java

public static void main(String[] args) throws IOException {

    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-01.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-01-145.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-02.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-03.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-04.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-05.jpg");
    //                 Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-01.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-04_resized.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\Camscanner Output\\normal_output_scan0007.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\Camscanner Output\\normal_output_scan0007-01.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\Camscanner Output\\normal_output_scan0001-01.bmp");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-300.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-96.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0001-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Thesis-4-1\\Previous Work\\OPenCv2\\eProthomAlo Sample I-O\\e-5-12.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Thesis-4-1\\Previous Work\\OPenCv2\\eProthomAlo Sample I-O\\e-6-12.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-300B.jpg");
    Mat inputImageMat = Highgui
            .imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-145B.jpg");
    if (null == inputImageMat) {
        System.out.println("[INPUT IMAGE NULL]");
    }//from w  w  w . j a  va 2 s. co  m
    Mat image = new Mat();//normal_output_scan0002.jpg
    double ratio = 150 / 72.0; // 4.167
    System.out.println("WIDTH: " + inputImageMat.width() + " HEIGHT:" + inputImageMat.height());
    int inputWidth = (int) (inputImageMat.width() * ratio);
    int inputHeight = (int) (inputImageMat.height() * ratio);
    System.out.println("WIDTH: " + inputWidth + " HEIGHT:" + inputHeight);

    //        inputImageMat = image;
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-02.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-03.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-04.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-05.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\web001.png");
    Debug.debugLog("[Image [Cols, Rows]: [" + inputImageMat.cols() + ", " + inputImageMat.rows() + "]]");
    //        imshow("Original", inputImageMat);
    ViewerUI.show("Original", inputImageMat, ViewableUI.SHOW_ORIGINAL);
    //        ViewerUI.show("Original-Histogram", Histogram.getHistogram(inputImageMat), ViewableUI.SHOW_HISTOGRAM_ORIGINAL);

    // Do some image processing on the image and display in another window.
    Mat filteredImage = new Mat();
    /**
     * We have explained some filters which main goal is to smooth an input
     * image. However, sometimes the filters do not only dissolve the noise,
     * but also smooth away the edges
     */
    //        Imgproc.bilateralFilter(inputImageMat, m2, -1, 50, 10); /*Previous line for noise filtering*/
    Imgproc.bilateralFilter(inputImageMat, filteredImage, -1, 50, 10);
    //        Imgproc.bilateralFilter(inputImageMat, filteredImage, -1, 150, 11);

    ViewerUI.show("Noise Filter", filteredImage, ViewableUI.SHOW_NOISE_FILTER);
    //        ViewerUI.show("Noise Filter-Histogram", Histogram.getHistogram(filteredImage), ViewableUI.SHOW_HISTOGRAM_NOISE_FILTER);
    Imgproc.Canny(filteredImage, filteredImage, 10, 150);
    //        Imgproc.bilateralFilter(filteredImage, filteredImage, -1, 50, 10);
    //        Imgproc.threshold(filteredImage, filteredImage, 250, 300,Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C );
    //Imgproc.cvtColor(m1, m1, Imgproc.COLOR_RGB2GRAY, 0);
    //        imshow("Edge Detected", m2);
    ViewerUI.show("Edge Detected", filteredImage, ViewableUI.SHOW_EDGE_DETECTION);
    //        ViewerUI.show("Edge Detected-Histogram", Histogram.getHistogram(filteredImage), ViewableUI.SHOW_HISTOGRAM_EDGE_DETECTION);

    Size sizeA = filteredImage.size();
    System.out.println("Width: " + sizeA.width + " Height: " + sizeA.height);
    int width = (int) sizeA.width;
    int height = (int) sizeA.height;
    int pointLength[][][] = new int[height][width][2];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            //double[] data = m2.get(i, j);
            if (filteredImage.get(i, j)[0] != 0) {
                pointLength[i][j][0] = 0;
                pointLength[i][j][1] = 0;
                continue;
            }
            if (j != 0 && filteredImage.get(i, j - 1)[0] == 0) {
                pointLength[i][j][0] = pointLength[i][j - 1][0];
            } else {
                int count = 0;
                for (int k = j + 1; k < width; k++) {
                    if (filteredImage.get(i, k)[0] == 0) {
                        count++;
                    } else {
                        break;
                    }
                }
                pointLength[i][j][0] = count;
            }
            if (i != 0 && filteredImage.get(i - 1, j)[0] == 0) {
                pointLength[i][j][1] = pointLength[i - 1][j][1];
            } else {
                int count = 0;
                for (int k = i + 1; k < height; k++) {
                    if (filteredImage.get(k, j)[0] == 0) {
                        count++;
                    } else {
                        break;
                    }
                }
                pointLength[i][j][1] = count;
            }
        }
    }
    String temp = "";
    Mat convertArea = filteredImage.clone();

    int[][] blackWhite = new int[height][width];

    for (int i = 0; i < height; i++) {
        temp = "";
        for (int j = 0; j < width; j++) {
            if (i == 0 || j == 0 || i == height - 1 || j == width - 1) {
                temp = temp + "@";
                blackWhite[i][j] = 1;

                double[] data = filteredImage.get(i, j);
                data[0] = 255.0;
                convertArea.put(i, j, data);
            } else if (pointLength[i][j][0] > 150 && pointLength[i][j][1] > 6) {
                temp = temp + "@";
                blackWhite[i][j] = 1;

                double[] data = filteredImage.get(i, j);
                data[0] = 255.0;
                convertArea.put(i, j, data);
            } else if (pointLength[i][j][0] > 7 && pointLength[i][j][1] > 200) {
                temp = temp + "@";
                blackWhite[i][j] = 1;

                double[] data = filteredImage.get(i, j);
                data[0] = 255.0;
                convertArea.put(i, j, data);
            } else {
                temp = temp + " ";
                blackWhite[i][j] = 0;

                double[] data = filteredImage.get(i, j);
                data[0] = 0.0;
                convertArea.put(i, j, data);
            }

        }
    }
    ViewerUI.show("Convertion", convertArea, ViewableUI.SHOW_CONVERSION);
    //        ViewerUI.show("Convertion-Histogram", Histogram.getHistogram(convertArea), ViewableUI.SHOW_HISTOGRAM_CONVERSION);

    ImageDetection isImage = new ImageDetection();
    HeadlineDetection isHeadline = new HeadlineDetection();

    ImageBorderDetectionBFS imgBFS = new ImageBorderDetectionBFS();
    ArrayList<BorderItem> borderItems = imgBFS.getBorder(blackWhite, width, height, filteredImage,
            inputImageMat);
    // Mat[] subMat = new Mat[borderItems.size()];
    //        for (int i = 0; i < borderItems.size(); i++) {
    //            subMat[i] = m2.submat(borderItems.get(i).getMinX(), borderItems.get(i).getMaxX(),
    //                    borderItems.get(i).getMinY(), borderItems.get(i).getMaxY());
    //            if (isImage.isImage(subMat[i])) {
    //                System.out.println("subMat" + i + " is an image");
    //                imshow("Image" + i, subMat[i]);
    //
    //            }else if(isHeadline.isHeadLine(subMat[i])){
    //                System.out.println("subMat" + i + " is an Headline");
    //                imshow("Headline" + i, subMat[i]);
    //            }else{
    //                System.out.println("subMat" + i + " is an Column");
    //                imshow("Column" + i, subMat[i]);
    //            }
    //            //imshow("subMat" + i, subMat[i]);
    //            bw.close();
    //
    //        }

    boolean[] imageIndexer = new boolean[borderItems.size()];
    int[] lineHeight = new int[borderItems.size()];
    int highestLinheight = -1, lowestLineHeight = 10000;
    int totalHeight = 0, notImage = 0;

    for (int i = 0; i < borderItems.size(); i++) {
        lineHeight[i] = 0;
        BorderItem borderItem = borderItems.get(i);
        //            subMat[i] = m2.submat(borderItems.get(i).getMinX(), borderItems.get(i).getMaxX(),
        //                    borderItems.get(i).getMinY(), borderItems.get(i).getMaxY());
        //            if (isImage.isImage(subMat[i])) {
        //                System.out.println("subMat" + i + " is an image");
        //                imshow("Image" + i, subMat[i]);
        //                imageIndexer[i] = true;
        //                continue;
        //            }else{
        //                notImage++;
        //                imageIndexer[i] = false;
        //            }
        if (borderItem.getIsImage()) {
            System.out.println("subMat" + i + " is an image");
            //                imshow("Image" + i, borderItem.getBlock());
            ViewerUI.show("Image" + i, borderItem.getBlock(), ViewableUI.SHOW_IMAGE);
            //                ViewerUI.show("Image-Histogram" + i, Histogram.getHistogram(borderItem.getBlock()), ViewableUI.SHOW_HISTOGRAM_IMAGE);

            imageIndexer[i] = true;
            continue;
        } else {
            notImage++;
            imageIndexer[i] = false;
        }

        //            totalHeight += lineHeight[i] = getLineHeight(subMat[i]);
        Mat fake = new Mat();
        Imgproc.cvtColor(borderItem.getBlock(), fake, Imgproc.COLOR_RGB2GRAY, 0);
        totalHeight += lineHeight[i] = getLineHeight(fake);
        fake.release();
        System.out.println("line height " + i + ": " + lineHeight[i]);
        //            imshow("" + i, borderItems.get(i).getBlock());
        if (lineHeight[i] > highestLinheight) {
            highestLinheight = lineHeight[i];
        }
        if (lineHeight[i] < lowestLineHeight) {
            lowestLineHeight = lineHeight[i];
        }

        //            if(i==7)
        //                break;
    }

    int avgLineHeight = totalHeight / notImage;

    for (int i = 0; i < borderItems.size(); i++) {
        if (!imageIndexer[i]) {
            if (lineHeight[i] - lowestLineHeight > 13 && lineHeight[i] >= 45) {
                //                    imshow("Headline" + i, subMat[i]);
                //                    imshow("Headline" + i, borderItems.get(i).getBlock());
                ViewerUI.show("Headline" + i, borderItems.get(i).getBlock(), ViewableUI.SHOW_HEADING);
                //                    ViewerUI.show("Headline-Histogram" + i, Histogram.getHistogram(borderItems.get(i).getBlock()), ViewableUI.SHOW_HISTOGRAM_HEADING);

            } else if (lineHeight[i] - lowestLineHeight > 8 && lineHeight[i] >= 21 && lineHeight[i] < 45) {
                //                    imshow("Sub Headline" + i, borderItems.get(i).getBlock());
                ViewerUI.show("Sub Headline" + i, borderItems.get(i).getBlock(), ViewableUI.SHOW_SUB_HEADING);
                //                    ViewerUI.show("Sub Headline-Histogram" + i, Histogram.getHistogram(borderItems.get(i).getBlock()), ViewableUI.SHOW_HISTOGRAM_SUB_HEADING);

            } else {
                //                    imshow("Column" + i, subMat[i]);
                //                    imshow("Column" + i, borderItems.get(i).getBlock());
                ViewerUI.show("Column" + i, borderItems.get(i).getBlock(), ViewableUI.SHOW_COLUMN);
                //                    ViewerUI.show("Column-Histogram" + i, Histogram.getHistogram(borderItems.get(i).getBlock()), ViewableUI.SHOW_HISTOGRAM_COLUMN);

            }
        }
    }

}

From source file:edu.sust.cse.util.Histogram.java

public static Mat getHistogram(Mat image) {

    try {/* ww w . ja v a  2  s .c  o  m*/
        Mat src = new Mat(image.height(), image.width(), CvType.CV_8UC2);
        Imgproc.cvtColor(image, src, Imgproc.COLOR_RGB2GRAY);
        ArrayList<Mat> bgr_planes = new ArrayList<>();
        Core.split(src, bgr_planes);

        MatOfInt histSize = new MatOfInt(256);

        final MatOfFloat histRange = new MatOfFloat(0f, 256f);

        boolean accumulate = false;

        Mat b_hist = new Mat();

        Imgproc.calcHist(bgr_planes, new MatOfInt(0), new Mat(), b_hist, histSize, histRange, accumulate);

        int hist_w = 512;
        int hist_h = 600;
        long bin_w;
        bin_w = Math.round((double) (hist_w / 256));

        Mat histImage = new Mat(hist_h, hist_w, CvType.CV_8UC1);

        Core.normalize(b_hist, b_hist, 3, histImage.rows(), Core.NORM_MINMAX);

        for (int i = 1; i < 256; i++) {

            Core.line(histImage, new Point(bin_w * (i - 1), hist_h - Math.round(b_hist.get(i - 1, 0)[0])),
                    new Point(bin_w * (i), hist_h - Math.round(Math.round(b_hist.get(i, 0)[0]))),
                    new Scalar(255, 0, 0), 2, 8, 0);

        }

        return histImage;
    } catch (Exception ex) {
        System.out.println("[HISTOGRAM][ERROR][" + ex.getMessage() + "]");
        return null;
    }
}

From source file:emotion.StaticFunctions.java

static public Mat convolution(int[] mask, Mat image) {
    if (mask.length != 9)
        return null;

    //output image
    Mat destination = new Mat(image.rows(), image.cols(), image.type());

    //Convolution kernel
    Mat kernel = new Mat(3, 3, CvType.CV_32F) {
        {/*from   w w  w  .  j a v  a  2 s  . com*/
            for (int i = 0, it = 0; i < 3; ++i) {
                for (int j = 0; j < 3; ++j, ++it) {
                    put(i, j, mask[it]);
                }
            }

        }
    };

    Imgproc.filter2D(image, destination, -1, kernel);

    imwrite("convol.jpg", destination);
    return destination;
}

From source file:es.ugr.osgiliart.drawer.OpenCVCollageDrawer.java

License:Open Source License

@Override
public void draw(ArtisticIndividual artistic) {
    /*//from  ww  w .java  2 s  .  com
     *  
     */

    int imageWidth = (Integer) this.getAlgorithmParameters().getParameter(ArtisticParameters.IMAGE_WIDTH);
    int imageHeight = (Integer) this.getAlgorithmParameters().getParameter(ArtisticParameters.IMAGE_HEIGHT);
    String imageType = (String) this.getAlgorithmParameters().getParameter(ArtisticParameters.IMAGE_TYPE);
    String folderPath = (String) this.getAlgorithmParameters().getParameter(ArtisticParameters.DATA_FOLDER);

    List<Primitive> primitives = ((ArtisticGenome) artistic.getGenome()).getPrimitives();
    Mat orig = new Mat(imageWidth, imageHeight, CvType.CV_8UC3, new Scalar(255, 255, 255));

    for (Primitive p : primitives) {
        Patch patch = (Patch) p;
        Mat pm = patch.getMat();
        int posCol = (int) (patch.getLocation().x * orig.cols());
        int posRow = (int) (patch.getLocation().y * orig.rows());
        int finalCol = posCol + pm.cols();
        int finalRow = posRow + pm.rows();

        if (finalCol > orig.cols())
            finalCol = orig.cols();
        if (finalRow > orig.rows())
            finalRow = orig.rows();
        //System.out.println("Poniendo imagen de tamao "+pm.rows()+","+pm.cols()+" en "+posRow+","+posCol+" hasta "+finalRow+","+finalCol);
        Mat bSubmat = orig.submat(posRow, finalRow, posCol, finalCol);

        pm.copyTo(bSubmat);

    }
    /*
     * draw image
     ****************************************************/

    /*save image */
    String imageExtension = null;
    if (imageType.equalsIgnoreCase(IMAGE_TYPE_JPEG)) {
        imageExtension = "jpg";
    } else if (imageType.equalsIgnoreCase(IMAGE_TYPE_PNG)) {
        imageExtension = "png";
    }

    if (imageExtension != null) {
        String imagePath = String.format("%s/%s.%s", folderPath, artistic.getId(), imageExtension);
        //System.out.println("Saving... " + imagePath + " primitives: " + primitives.size());
        //graphics.save(imagePath);
        //applet.save(imagePath);
        Highgui.imwrite(imagePath, orig);
        artistic.setImagePath(imagePath);
    }
}

From source file:facedetection.FaceDetector.java

public BufferedImage mat2BufferedImage(Mat m) {
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }/*w ww  .  j  av a2  s  .  c om*/
    int bufferSize = m.channels() * m.cols() * m.rows();
    byte[] b = new byte[bufferSize];
    m.get(0, 0, b); // get all the pixels
    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);
    return image;

}

From source file:faceDetectionV1.FaceDetection.java

private BufferedImage convertMatToImage(Mat matrix) {
    int type = BufferedImage.TYPE_BYTE_GRAY;

    if (matrix.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }/*from  w  w w.  j a  v  a  2  s.  c o m*/

    int bufferSize = matrix.channels() * matrix.cols() * matrix.rows();
    byte bytes[] = new byte[bufferSize];
    matrix.get(0, 0, bytes);
    BufferedImage image = new BufferedImage(matrix.cols(), matrix.rows(), type);
    final byte targetsize[] = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(bytes, 0, targetsize, 0, bytes.length);
    return image;
}

From source file:finalpro.FinalPro.java

public static String threshholding() {
    Mat destination = null;//www .  j  av  a  2 s  .  c  o m
    Mat source = null;
    String str = "";
    try {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        source = Imgcodecs.imread("C:/QuadPotroler/FinalPro/src/images/20151207_153915.jpg",
                Imgcodecs.CV_LOAD_IMAGE_COLOR);
        destination = new Mat(source.rows(), source.cols(), source.type());
        destination = source;
        Imgproc.threshold(source, destination, 127, 255, Imgproc.THRESH_TOZERO);
        Imgcodecs.imwrite("C:/QuadPotroler/FinalPro/src/images/threshdold.jpg", destination);
        str = "C:/QuadPotroler/FinalPro/src/images/threshdold.jpg";
    } catch (Exception e) {
        System.out.println("error: " + e.getMessage());
    }
    return str;
}

From source file:fr.olympicinsa.riocognized.facedetector.tools.ImageConvertor.java

/**
 * Converts/writes a Mat into a BufferedImage.
 *
 * @param matrix Mat of type CV_8UC3 or CV_8UC1
 * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
 *///from w w  w . j a va2  s.co  m
public static BufferedImage matToBufferedImage(Mat matrix) {
    log.debug("****** MatToBuffered Image **********");
    log.debug("input : " + matrix.toString());
    int cols = matrix.cols();
    int rows = matrix.rows();
    int elemSize = (int) matrix.elemSize();
    byte[] data = new byte[cols * rows * elemSize];
    int type;

    matrix.get(0, 0, data);

    switch (matrix.channels()) {
    case 1:
        type = BufferedImage.TYPE_BYTE_GRAY;
        break;

    case 3:
        type = BufferedImage.TYPE_3BYTE_BGR;

        // bgr to rgb
        byte b;
        for (int i = 0; i < data.length; i = i + 3) {
            b = data[i];
            data[i] = data[i + 2];
            data[i + 2] = b;
        }
        break;

    default:
        return null;
    }

    BufferedImage image = new BufferedImage(cols, rows, type);
    image.getRaster().setDataElements(0, 0, cols, rows, data);
    log.debug("type: " + type);
    log.debug("output:" + image.toString());
    log.debug("***********************************");
    return image;
}

From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java

License:Apache License

static ArrayList<double[][]> computeGradients(Mat frame, int dim) {
    byte frame_array[] = new byte[(int) frame.total()];
    frame.get(0, 0, frame_array);//from w w  w  .ja  v a  2s  .  com

    ArrayList<double[][]> gradients = new ArrayList<double[][]>();

    for (int k = 0; k < dim; k++) {
        double angle = Math.PI * (double) k / (double) dim;

        double dx = Math.cos(angle) * 0.9999999;
        double dy = Math.sin(angle) * 0.9999999;

        double[][] grad = new double[frame.width()][frame.height()];

        for (int i = 0; i < frame.cols(); i++) {
            for (int j = 0; j < frame.rows(); j++) {
                if (i <= 1 || j <= 1 || i >= frame.cols() - 2 || j >= frame.rows() - 2) {
                    grad[i][j] = 0;
                } else {
                    double f1 = interpolatePixel(frame_array, frame.cols(), (double) i + dx, (double) j + dy);
                    double f2 = interpolatePixel(frame_array, frame.cols(), (double) i - dx, (double) j - dy);

                    double diff = f1 - f2;
                    if (diff < 0)
                        diff = diff * -1;
                    if (diff >= 256)
                        diff = 255;

                    grad[i][j] = diff;
                }
            }
        }

        gradients.add(grad);
    }

    return gradients;
}

From source file:houghtransform.transform_process.MyTransform.java

@Override
public void houghTransform(Mat edges) {
    Mat _edges = edges.clone();

    double radian = Math.PI / 180;
    int degrees = (int) Math.floor(theta * 180 / Math.PI + 0.5);

    int w = _edges.cols();
    int h = _edges.rows();

    _edges.convertTo(_edges, CvType.CV_64FC3);
    int size = w * h;
    double[] img_data = new double[size];
    _edges.get(0, 0, img_data); // Gets all pixels

    _img_w = w; //Number of columns
    _img_h = h; //Number of lines

    //Create the accumulator
    double hough_h = ((Math.sqrt(2.0) * (double) (h > w ? h : w)) / 2.0);
    _accu_h = (int) (hough_h * 2.0); // -r -> +r
    _accu_w = 180;/*from  ww  w  .  j a  va  2s .  co  m*/

    _accu = new int[_accu_h * _accu_w];
    for (int i = 0; i < _accu_h * _accu_w; i++) {
        _accu[i] = 0;
    }

    double center_x = w / 2;
    double center_y = h / 2;

    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            if (img_data[(y * w) + x] > 250) {
                for (int t = 0; t < 180; t = t + degrees) {
                    // y = x * cos( theta ) + y * sin( theta )
                    double r = (((double) x - center_x) * Math.cos((double) t * radian))
                            + (((double) y - center_y) * Math.sin((double) t * radian));
                    _accu[(int) ((Math.floor(r + hough_h) * 180.0)) + t]++;
                }
            }
        }
    }

    ArrayList<Point> lines = new ArrayList<>();

    if (_accu.length == 0)
        try {
            throw new IOException("MyTransform: _accu == 0");
        } catch (IOException ex) {
            System.out.println(ex);
        }

    for (int r = 0; r < _accu_h; r++) {
        for (int t = 0; t < _accu_w; t++) {
            // Searching in the accumulator a value greater
            //or equal to the set threshold
            if (((int) _accu[(r * _accu_w) + t]) >= threshold) {
                // Is this point a local maxima (9x9)
                int max = _accu[(r * _accu_w) + t];
                ////////////////////////////////
                for (int ly = -4; ly <= 4; ly++) {
                    for (int lx = -4; lx <= 4; lx++) {
                        if (((ly + r) >= 0 && (ly + r) < _accu_h) && ((lx + t) >= 0 && (lx + t) < _accu_w)) {
                            if ((int) _accu[((r + ly) * _accu_w) + (t + lx)] > max) {
                                max = _accu[((r + ly) * _accu_w) + (t + lx)];
                                ly = lx = 5;
                            }
                        }
                    }
                }
                /////////////////////////////////
                if (max > (int) _accu[(r * _accu_w) + t])
                    continue;

                Point point = new Point();
                point.x = r;
                point.y = t * radian;
                lines.add(point);
            }
        }
    }
    _lines = lines;
}