Add Java and Python code for the following tutorials:
[platform/upstream/opencv.git] / samples / python / tutorial_code / core / mat_operations / mat_operations.py
1 from __future__ import division
2 import cv2 as cv
3 import numpy as np
4
5 # Snippet code for Operations with images tutorial (not intended to be run)
6
7 def load():
8     # Input/Output
9     filename = 'img.jpg'
10     ## [Load an image from a file]
11     img = cv.imread(filename)
12     ## [Load an image from a file]
13
14     ## [Load an image from a file in grayscale]
15     img = cv.imread(filename, cv.IMREAD_GRAYSCALE)
16     ## [Load an image from a file in grayscale]
17
18     ## [Save image]
19     cv.imwrite(filename, img)
20     ## [Save image]
21
22 def access_pixel():
23     # Accessing pixel intensity values
24     img = np.empty((4,4,3), np.uint8)
25     y = 0
26     x = 0
27     ## [Pixel access 1]
28     intensity = img[y,x]
29     ## [Pixel access 1]
30
31     ## [Pixel access 3]
32     blue = img[y,x,0]
33     green = img[y,x,1]
34     red = img[y,x,2]
35     ## [Pixel access 3]
36
37     ## [Pixel access 5]
38     img[y,x] = 128
39     ## [Pixel access 5]
40
41 def reference_counting():
42     # Memory management and reference counting
43     ## [Reference counting 2]
44     img = cv.imread('image.jpg')
45     img1 = np.copy(img)
46     ## [Reference counting 2]
47
48     ## [Reference counting 3]
49     img = cv.imread('image.jpg')
50     sobelx = cv.Sobel(img, cv.CV_32F, 1, 0);
51     ## [Reference counting 3]
52
53 def primitive_operations():
54     img = np.empty((4,4,3), np.uint8)
55     ## [Set image to black]
56     img[:] = 0
57     ## [Set image to black]
58
59     ## [Select ROI]
60     smallImg = img[10:110,10:110]
61     ## [Select ROI]
62
63     ## [BGR to Gray]
64     img = cv.imread('image.jpg')
65     grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
66     ## [BGR to Gray]
67
68     src = np.ones((4,4), np.uint8)
69     ## [Convert to CV_32F]
70     dst = src.astype(np.float32)
71     ## [Convert to CV_32F]
72
73 def visualize_images():
74     ## [imshow 1]
75     img = cv.imread('image.jpg')
76     cv.namedWindow('image', cv.WINDOW_AUTOSIZE)
77     cv.imshow('image', img)
78     cv.waitKey()
79     ## [imshow 1]
80
81     ## [imshow 2]
82     img = cv.imread('image.jpg')
83     grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
84     sobelx = cv.Sobel(grey, cv.CV_32F, 1, 0)
85     # find minimum and maximum intensities
86     minVal = np.amin(sobelx)
87     maxVal = np.amax(sobelx)
88     draw = cv.convertScaleAbs(sobelx, alpha=255.0/(maxVal - minVal), beta=-minVal * 255.0/(maxVal - minVal))
89     cv.namedWindow('image', cv.WINDOW_AUTOSIZE)
90     cv.imshow('image', draw)
91     cv.waitKey()
92     ## [imshow 2]