Commit 89172c08 authored by Alexander Alekhin's avatar Alexander Alekhin

Merge pull request #9049 from Cartucho:improve_mask_tutorial_codes

parents a2120263 d53a5210
...@@ -12,7 +12,7 @@ static void help(char* progName) ...@@ -12,7 +12,7 @@ static void help(char* progName)
<< "This program shows how to filter images with mask: the write it yourself and the" << "This program shows how to filter images with mask: the write it yourself and the"
<< "filter2d way. " << endl << "filter2d way. " << endl
<< "Usage:" << endl << "Usage:" << endl
<< progName << " [image_name -- default ../data/lena.jpg] [G -- grayscale] " << endl << endl; << progName << " [image_path -- default ../data/lena.jpg] [G -- grayscale] " << endl << endl;
} }
...@@ -45,7 +45,7 @@ int main( int argc, char* argv[]) ...@@ -45,7 +45,7 @@ int main( int argc, char* argv[])
Sharpen( src, dst0 ); Sharpen( src, dst0 );
t = ((double)getTickCount() - t)/getTickFrequency(); t = ((double)getTickCount() - t)/getTickFrequency();
cout << "Hand written function times passed in seconds: " << t << endl; cout << "Hand written function time passed in seconds: " << t << endl;
imshow( "Output", dst0 ); imshow( "Output", dst0 );
waitKey(); waitKey();
......
import org.opencv.core.*; import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc; import org.opencv.imgproc.Imgproc;
import javax.swing.*; import javax.swing.*;
import java.awt.Image; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte; import java.awt.image.DataBufferByte;
class MatMaskOperationsRun { class MatMaskOperationsRun {
public void run() { public void run(String[] args) {
//! [laod_image] String filename = "../data/lena.jpg";
Mat I = Imgcodecs.imread("../data/lena.jpg");
if(I.empty())
System.out.println("Error opening image");
//! [laod_image]
Image img = toBufferedImage( I ); int img_codec = Imgcodecs.IMREAD_COLOR;
displayImage("Input Image" , img, 0, 200 ); if (args.length != 0) {
filename = args[0];
if (args.length >= 2 && args[1].equals("G"))
img_codec = Imgcodecs.IMREAD_GRAYSCALE;
}
Mat src = Imgcodecs.imread(filename, img_codec);
if (src.empty()) {
System.out.println("Can't open image [" + filename + "]");
System.out.println("Program Arguments: [image_path -- default ../data/lena.jpg] [G -- grayscale]");
System.exit(-1);
}
Image img = toBufferedImage(src);
displayImage("Input", img, 0, 200);
double t = System.currentTimeMillis(); double t = System.currentTimeMillis();
Mat J = sharpen(I, new Mat()); Mat dst0 = sharpen(src, new Mat());
t = ((double)System.currentTimeMillis() - t)/1000; t = ((double) System.currentTimeMillis() - t) / 1000;
System.out.println("Hand written function times passed in seconds: " + t); System.out.println("Hand written function time passed in seconds: " + t);
Image img2 = toBufferedImage( J ); Image img2 = toBufferedImage(dst0);
displayImage("Output Image" , img2, 400, 400 ); displayImage("Output", img2, 400, 400);
Mat K = new Mat();
//![kern] //![kern]
Mat kern = new Mat( 3, 3, CvType.CV_8S ); Mat kern = new Mat(3, 3, CvType.CV_8S);
int row = 0, col = 0; int row = 0, col = 0;
kern.put(row ,col, 0, -1, 0, -1, 5, -1, 0, -1, 0 ); kern.put(row, col, 0, -1, 0, -1, 5, -1, 0, -1, 0);
//![kern] //![kern]
System.out.println("kern = \n" + kern.dump());
t = System.currentTimeMillis(); t = System.currentTimeMillis();
Mat dst1 = new Mat();
//![filter2D] //![filter2D]
Imgproc.filter2D(I, K, I.depth(), kern ); Imgproc.filter2D(src, dst1, src.depth(), kern);
//![filter2D] //![filter2D]
t = ((double) System.currentTimeMillis() - t) / 1000;
t = ((double)System.currentTimeMillis() - t)/1000;
System.out.println("Built-in filter2D time passed in seconds: " + t); System.out.println("Built-in filter2D time passed in seconds: " + t);
Image img3 = toBufferedImage( J ); Image img3 = toBufferedImage(dst1);
displayImage("filter2D Output Image" , img3, 800, 400 ); displayImage("Output", img3, 800, 400);
} }
//! [basic_method] //! [basic_method]
public static double saturateCastUchar(double x) { public static double saturate(double x) {
return x > 255.0 ? 255.0 : (x < 0.0 ? 0.0 : x); return x > 255.0 ? 255.0 : (x < 0.0 ? 0.0 : x);
} }
public Mat sharpen(Mat myImage, Mat Result) public Mat sharpen(Mat myImage, Mat Result) {
{
//! [8_bit] //! [8_bit]
myImage.convertTo(myImage, CvType.CV_8U); myImage.convertTo(myImage, CvType.CV_8U);
//! [8_bit] //! [8_bit]
//! [create_channels] //! [create_channels]
int nChannels = myImage.channels(); int nChannels = myImage.channels();
Result.create(myImage.size(),myImage.type()); Result.create(myImage.size(), myImage.type());
//! [create_channels] //! [create_channels]
//! [basic_method_loop] //! [basic_method_loop]
for(int j = 1 ; j < myImage.rows()-1; ++j) for (int j = 1; j < myImage.rows() - 1; ++j) {
{ for (int i = 1; i < myImage.cols() - 1; ++i) {
for(int i = 1 ; i < myImage.cols()-1; ++i)
{
double sum[] = new double[nChannels]; double sum[] = new double[nChannels];
for(int k = 0; k < nChannels; ++k) { for (int k = 0; k < nChannels; ++k) {
double top = -myImage.get(j - 1, i)[k]; double top = -myImage.get(j - 1, i)[k];
double bottom = -myImage.get(j + 1, i)[k]; double bottom = -myImage.get(j + 1, i)[k];
double center = (5 * myImage.get(j, i)[k]); double center = (5 * myImage.get(j, i)[k]);
double left = -myImage.get(j , i - 1)[k]; double left = -myImage.get(j, i - 1)[k];
double right = -myImage.get(j , i + 1)[k]; double right = -myImage.get(j, i + 1)[k];
sum[k] = saturateCastUchar(top + bottom + center + left + right); sum[k] = saturate(top + bottom + center + left + right);
} }
Result.put(j, i, sum); Result.put(j, i, sum);
...@@ -93,9 +100,9 @@ class MatMaskOperationsRun { ...@@ -93,9 +100,9 @@ class MatMaskOperationsRun {
//! [borders] //! [borders]
Result.row(0).setTo(new Scalar(0)); Result.row(0).setTo(new Scalar(0));
Result.row(Result.rows()-1).setTo(new Scalar(0)); Result.row(Result.rows() - 1).setTo(new Scalar(0));
Result.col(0).setTo(new Scalar(0)); Result.col(0).setTo(new Scalar(0));
Result.col(Result.cols()-1).setTo(new Scalar(0)); Result.col(Result.cols() - 1).setTo(new Scalar(0));
//! [borders] //! [borders]
return Result; return Result;
...@@ -104,23 +111,22 @@ class MatMaskOperationsRun { ...@@ -104,23 +111,22 @@ class MatMaskOperationsRun {
public Image toBufferedImage(Mat m) { public Image toBufferedImage(Mat m) {
int type = BufferedImage.TYPE_BYTE_GRAY; int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) { if (m.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR; type = BufferedImage.TYPE_3BYTE_BGR;
} }
int bufferSize = m.channels()*m.cols()*m.rows(); int bufferSize = m.channels() * m.cols() * m.rows();
byte [] b = new byte[bufferSize]; byte[] b = new byte[bufferSize];
m.get(0,0,b); // get all the pixels m.get(0, 0, b); // get all the pixels
BufferedImage image = new BufferedImage(m.cols(),m.rows(), type); BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length); System.arraycopy(b, 0, targetPixels, 0, b.length);
return image; return image;
} }
public void displayImage(String title, Image img, int x, int y) public void displayImage(String title, Image img, int x, int y) {
{ ImageIcon icon = new ImageIcon(img);
ImageIcon icon=new ImageIcon(img); JFrame frame = new JFrame(title);
JFrame frame=new JFrame(title); JLabel lbl = new JLabel(icon);
JLabel lbl=new JLabel(icon);
frame.add(lbl); frame.add(lbl);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); frame.pack();
...@@ -131,9 +137,9 @@ class MatMaskOperationsRun { ...@@ -131,9 +137,9 @@ class MatMaskOperationsRun {
public class MatMaskOperations { public class MatMaskOperations {
public static void main(String[] args) { public static void main(String[] args) {
// Load the native library. // Load the native library.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
new MatMaskOperationsRun().run();
new MatMaskOperationsRun().run(args); // run code
} }
} }
import sys
import time import time
import numpy as np import numpy as np
import cv2 import cv2
## [basic_method] ## [basic_method]
def is_grayscale(my_image):
return len(my_image.shape) < 3
def saturated(sum_value):
if sum_value > 255:
sum_value = 255
if sum_value < 0:
sum_value = 0
return sum_value
def sharpen(my_image): def sharpen(my_image):
if is_grayscale(my_image):
height, width = my_image.shape
else:
my_image = cv2.cvtColor(my_image, cv2.CV_8U) my_image = cv2.cvtColor(my_image, cv2.CV_8U)
height, width, n_channels = my_image.shape height, width, n_channels = my_image.shape
result = np.zeros(my_image.shape, my_image.dtype) result = np.zeros(my_image.shape, my_image.dtype)
## [basic_method_loop] ## [basic_method_loop]
for j in range (1, height-1): for j in range(1, height - 1):
for i in range (1, width-1): for i in range(1, width - 1):
for k in range (0, n_channels): if is_grayscale(my_image):
sum = 5 * my_image[j, i, k] - my_image[j + 1, i, k] - my_image[j - 1, i, k]\ sum_value = 5 * my_image[j, i] - my_image[j + 1, i] - my_image[j - 1, i] \
- my_image[j, i + 1, k] - my_image[j, i - 1, k]; - my_image[j, i + 1] - my_image[j, i - 1]
result[j, i] = saturated(sum_value)
if sum > 255: else:
sum = 255 for k in range(0, n_channels):
if sum < 0: sum_value = 5 * my_image[j, i, k] - my_image[j + 1, i, k] - my_image[j - 1, i, k] \
sum = 0 - my_image[j, i + 1, k] - my_image[j, i - 1, k]
result[j, i, k] = saturated(sum_value)
result[j, i, k] = sum
## [basic_method_loop] ## [basic_method_loop]
return result return result
## [basic_method] ## [basic_method]
I = cv2.imread("../data/lena.jpg") def main(argv):
cv2.imshow('Input Image', I) filename = "../data/lena.jpg"
img_codec = cv2.IMREAD_COLOR
if argv:
filename = sys.argv[1]
if len(argv) >= 2 and sys.argv[2] == "G":
img_codec = cv2.IMREAD_GRAYSCALE
src = cv2.imread(filename, img_codec)
if src is None:
print "Can't open image [" + filename + "]"
print "Usage:\nmat_mask_operations.py [image_path -- default ../data/lena.jpg] [G -- grayscale]"
return -1
cv2.namedWindow("Input", cv2.WINDOW_AUTOSIZE)
cv2.namedWindow("Output", cv2.WINDOW_AUTOSIZE)
cv2.imshow("Input", src)
t = round(time.time())
dst0 = sharpen(src)
t = (time.time() - t) / 1000
print "Hand written function time passed in seconds: %s" % t
cv2.imshow("Output", dst0)
cv2.waitKey()
t = round(time.time()) t = time.time()
J = sharpen(I) ## [kern]
t = (time.time() - t)/1000 kernel = np.array([[0, -1, 0],
print "Hand written function times passed in seconds: %s" % t [-1, 5, -1],
[0, -1, 0]], np.float32) # kernel should be floating point type
## [kern]
cv2.imshow('Output Image', J) ## [filter2D]
dst1 = cv2.filter2D(src, -1, kernel) # ddepth = -1, means destination image has depth same as input image
## [filter2D]
t = time.time() t = (time.time() - t) / 1000
## [kern] print "Built-in filter2D time passed in seconds: %s" % t
kernel = np.array([ [0,-1,0],
[-1,5,-1],
[0,-1,0] ],np.float32) # kernel should be floating point type
## [kern]
## [filter2D] cv2.imshow("Output", dst1)
K = cv2.filter2D(I, -1, kernel) # ddepth = -1, means destination image has depth same as input image.
## [filter2D]
t = (time.time() - t)/1000 cv2.waitKey(0)
print "Built-in filter2D time passed in seconds: %s" % t cv2.destroyAllWindows()
return 0
cv2.imshow('filter2D Output Image', K)
cv2.waitKey(0) if __name__ == "__main__":
cv2.destroyAllWindows() main(sys.argv[1:])
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment