mirror of
https://gitcode.com/gh_mirrors/es/esp32-opencv.git
synced 2025-08-15 03:01:04 +08:00
initial commit
This commit is contained in:
@ -0,0 +1,36 @@
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2 as cv
|
||||
|
||||
alpha = 0.5
|
||||
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
print(''' Simple Linear Blender
|
||||
-----------------------
|
||||
* Enter alpha [0.0-1.0]: ''')
|
||||
input_alpha = float(raw_input().strip())
|
||||
if 0 <= alpha <= 1:
|
||||
alpha = input_alpha
|
||||
# [load]
|
||||
src1 = cv.imread(cv.samples.findFile('LinuxLogo.jpg'))
|
||||
src2 = cv.imread(cv.samples.findFile('WindowsLogo.jpg'))
|
||||
# [load]
|
||||
if src1 is None:
|
||||
print("Error loading src1")
|
||||
exit(-1)
|
||||
elif src2 is None:
|
||||
print("Error loading src2")
|
||||
exit(-1)
|
||||
# [blend_images]
|
||||
beta = (1.0 - alpha)
|
||||
dst = cv.addWeighted(src1, alpha, src2, beta, 0.0)
|
||||
# [blend_images]
|
||||
# [display]
|
||||
cv.imshow('dst', dst)
|
||||
cv.waitKey(0)
|
||||
# [display]
|
||||
cv.destroyAllWindows()
|
@ -0,0 +1,80 @@
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
|
||||
def print_help():
|
||||
print('''
|
||||
This program demonstrated the use of the discrete Fourier transform (DFT).
|
||||
The dft of an image is taken and it's power spectrum is displayed.
|
||||
Usage:
|
||||
discrete_fourier_transform.py [image_name -- default lena.jpg]''')
|
||||
|
||||
|
||||
def main(argv):
|
||||
|
||||
print_help()
|
||||
|
||||
filename = argv[0] if len(argv) > 0 else 'lena.jpg'
|
||||
|
||||
I = cv.imread(cv.samples.findFile(filename), cv.IMREAD_GRAYSCALE)
|
||||
if I is None:
|
||||
print('Error opening image')
|
||||
return -1
|
||||
## [expand]
|
||||
rows, cols = I.shape
|
||||
m = cv.getOptimalDFTSize( rows )
|
||||
n = cv.getOptimalDFTSize( cols )
|
||||
padded = cv.copyMakeBorder(I, 0, m - rows, 0, n - cols, cv.BORDER_CONSTANT, value=[0, 0, 0])
|
||||
## [expand]
|
||||
## [complex_and_real]
|
||||
planes = [np.float32(padded), np.zeros(padded.shape, np.float32)]
|
||||
complexI = cv.merge(planes) # Add to the expanded another plane with zeros
|
||||
## [complex_and_real]
|
||||
## [dft]
|
||||
cv.dft(complexI, complexI) # this way the result may fit in the source matrix
|
||||
## [dft]
|
||||
# compute the magnitude and switch to logarithmic scale
|
||||
# = > log(1 + sqrt(Re(DFT(I)) ^ 2 + Im(DFT(I)) ^ 2))
|
||||
## [magnitude]
|
||||
cv.split(complexI, planes) # planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
|
||||
cv.magnitude(planes[0], planes[1], planes[0])# planes[0] = magnitude
|
||||
magI = planes[0]
|
||||
## [magnitude]
|
||||
## [log]
|
||||
matOfOnes = np.ones(magI.shape, dtype=magI.dtype)
|
||||
cv.add(matOfOnes, magI, magI) # switch to logarithmic scale
|
||||
cv.log(magI, magI)
|
||||
## [log]
|
||||
## [crop_rearrange]
|
||||
magI_rows, magI_cols = magI.shape
|
||||
# crop the spectrum, if it has an odd number of rows or columns
|
||||
magI = magI[0:(magI_rows & -2), 0:(magI_cols & -2)]
|
||||
cx = int(magI_rows/2)
|
||||
cy = int(magI_cols/2)
|
||||
|
||||
q0 = magI[0:cx, 0:cy] # Top-Left - Create a ROI per quadrant
|
||||
q1 = magI[cx:cx+cx, 0:cy] # Top-Right
|
||||
q2 = magI[0:cx, cy:cy+cy] # Bottom-Left
|
||||
q3 = magI[cx:cx+cx, cy:cy+cy] # Bottom-Right
|
||||
|
||||
tmp = np.copy(q0) # swap quadrants (Top-Left with Bottom-Right)
|
||||
magI[0:cx, 0:cy] = q3
|
||||
magI[cx:cx + cx, cy:cy + cy] = tmp
|
||||
|
||||
tmp = np.copy(q1) # swap quadrant (Top-Right with Bottom-Left)
|
||||
magI[cx:cx + cx, 0:cy] = q2
|
||||
magI[0:cx, cy:cy + cy] = tmp
|
||||
## [crop_rearrange]
|
||||
## [normalize]
|
||||
cv.normalize(magI, magI, 0, 1, cv.NORM_MINMAX) # Transform the matrix with float values into a
|
||||
## viewable image form(float between values 0 and 1).
|
||||
## [normalize]
|
||||
cv.imshow("Input Image" , I ) # Show the result
|
||||
cv.imshow("spectrum magnitude", magI)
|
||||
cv.waitKey()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
@ -0,0 +1,156 @@
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
import sys
|
||||
|
||||
def help(filename):
|
||||
print (
|
||||
'''
|
||||
{0} shows the usage of the OpenCV serialization functionality. \n\n
|
||||
usage:\n
|
||||
python3 {0} outputfile.yml.gz\n\n
|
||||
The output file may be either in XML, YAML or JSON. You can even compress it\n
|
||||
by specifying this in its extension like xml.gz yaml.gz etc... With\n
|
||||
FileStorage you can serialize objects in OpenCV.\n\n
|
||||
For example: - create a class and have it serialized\n
|
||||
- use it to read and write matrices.\n
|
||||
'''.format(filename)
|
||||
)
|
||||
|
||||
class MyData:
|
||||
A = 97
|
||||
X = np.pi
|
||||
name = 'mydata1234'
|
||||
|
||||
def __repr__(self):
|
||||
s = '{ name = ' + self.name + ', X = ' + str(self.X)
|
||||
s = s + ', A = ' + str(self.A) + '}'
|
||||
return s
|
||||
|
||||
## [inside]
|
||||
def write(self, fs):
|
||||
fs.write('MyData','{')
|
||||
fs.write('A', self.A)
|
||||
fs.write('X', self.X)
|
||||
fs.write('name', self.name)
|
||||
fs.write('MyData','}')
|
||||
|
||||
def read(self, node):
|
||||
if (not node.empty()):
|
||||
self.A = int(node.getNode('A').real())
|
||||
self.X = node.getNode('X').real()
|
||||
self.name = node.getNode('name').string()
|
||||
else:
|
||||
self.A = self.X = 0
|
||||
self.name = ''
|
||||
## [inside]
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2:
|
||||
help(argv[0])
|
||||
exit(1)
|
||||
|
||||
# write
|
||||
## [iomati]
|
||||
R = np.eye(3,3)
|
||||
T = np.zeros((3,1))
|
||||
## [iomati]
|
||||
## [customIOi]
|
||||
m = MyData()
|
||||
## [customIOi]
|
||||
|
||||
filename = argv[1]
|
||||
|
||||
## [open]
|
||||
s = cv.FileStorage(filename, cv.FileStorage_WRITE)
|
||||
# or:
|
||||
# s = cv.FileStorage()
|
||||
# s.open(filename, cv.FileStorage_WRITE)
|
||||
## [open]
|
||||
|
||||
## [writeNum]
|
||||
s.write('iterationNr', 100)
|
||||
## [writeNum]
|
||||
|
||||
## [writeStr]
|
||||
s.write('strings', '[')
|
||||
s.write('image1.jpg','Awesomeness')
|
||||
s.write('../data/baboon.jpg',']')
|
||||
## [writeStr]
|
||||
|
||||
## [writeMap]
|
||||
s.write ('Mapping', '{')
|
||||
s.write ('One', 1)
|
||||
s.write ('Two', 2)
|
||||
s.write ('Mapping', '}')
|
||||
## [writeMap]
|
||||
|
||||
## [iomatw]
|
||||
s.write ('R_MAT', R)
|
||||
s.write ('T_MAT', T)
|
||||
## [iomatw]
|
||||
|
||||
## [customIOw]
|
||||
m.write(s)
|
||||
## [customIOw]
|
||||
## [close]
|
||||
s.release()
|
||||
## [close]
|
||||
print ('Write Done.')
|
||||
|
||||
# read
|
||||
print ('\nReading: ')
|
||||
s = cv.FileStorage()
|
||||
s.open(filename, cv.FileStorage_READ)
|
||||
|
||||
## [readNum]
|
||||
n = s.getNode('iterationNr')
|
||||
itNr = int(n.real())
|
||||
## [readNum]
|
||||
print (itNr)
|
||||
|
||||
if (not s.isOpened()):
|
||||
print ('Failed to open ', filename, file=sys.stderr)
|
||||
help(argv[0])
|
||||
exit(1)
|
||||
|
||||
## [readStr]
|
||||
n = s.getNode('strings')
|
||||
if (not n.isSeq()):
|
||||
print ('strings is not a sequence! FAIL', file=sys.stderr)
|
||||
exit(1)
|
||||
|
||||
for i in range(n.size()):
|
||||
print (n.at(i).string())
|
||||
## [readStr]
|
||||
|
||||
## [readMap]
|
||||
n = s.getNode('Mapping')
|
||||
print ('Two',int(n.getNode('Two').real()),'; ')
|
||||
print ('One',int(n.getNode('One').real()),'\n')
|
||||
## [readMap]
|
||||
|
||||
## [iomat]
|
||||
R = s.getNode('R_MAT').mat()
|
||||
T = s.getNode('T_MAT').mat()
|
||||
## [iomat]
|
||||
## [customIO]
|
||||
m.read(s.getNode('MyData'))
|
||||
## [customIO]
|
||||
|
||||
print ('\nR =',R)
|
||||
print ('T =',T,'\n')
|
||||
print ('MyData =','\n',m,'\n')
|
||||
|
||||
## [nonexist]
|
||||
print ('Attempt to read NonExisting (should initialize the data structure',
|
||||
'with its default).')
|
||||
m.read(s.getNode('NonExisting'))
|
||||
print ('\nNonExisting =','\n',m)
|
||||
## [nonexist]
|
||||
|
||||
print ('\nTip: Open up',filename,'with a text editor to see the serialized data.')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
@ -0,0 +1,100 @@
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
|
||||
## [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):
|
||||
if is_grayscale(my_image):
|
||||
height, width = my_image.shape
|
||||
else:
|
||||
my_image = cv.cvtColor(my_image, cv.CV_8U)
|
||||
height, width, n_channels = my_image.shape
|
||||
|
||||
result = np.zeros(my_image.shape, my_image.dtype)
|
||||
## [basic_method_loop]
|
||||
for j in range(1, height - 1):
|
||||
for i in range(1, width - 1):
|
||||
if is_grayscale(my_image):
|
||||
sum_value = 5 * my_image[j, i] - my_image[j + 1, i] - my_image[j - 1, i] \
|
||||
- my_image[j, i + 1] - my_image[j, i - 1]
|
||||
result[j, i] = saturated(sum_value)
|
||||
else:
|
||||
for k in range(0, n_channels):
|
||||
sum_value = 5 * my_image[j, i, k] - my_image[j + 1, i, k] \
|
||||
- my_image[j - 1, i, k] - my_image[j, i + 1, k]\
|
||||
- my_image[j, i - 1, k]
|
||||
result[j, i, k] = saturated(sum_value)
|
||||
## [basic_method_loop]
|
||||
return result
|
||||
## [basic_method]
|
||||
|
||||
def main(argv):
|
||||
filename = 'lena.jpg'
|
||||
|
||||
img_codec = cv.IMREAD_COLOR
|
||||
if argv:
|
||||
filename = sys.argv[1]
|
||||
if len(argv) >= 2 and sys.argv[2] == "G":
|
||||
img_codec = cv.IMREAD_GRAYSCALE
|
||||
|
||||
src = cv.imread(cv.samples.findFile(filename), img_codec)
|
||||
|
||||
if src is None:
|
||||
print("Can't open image [" + filename + "]")
|
||||
print("Usage:")
|
||||
print("mat_mask_operations.py [image_path -- default lena.jpg] [G -- grayscale]")
|
||||
return -1
|
||||
|
||||
cv.namedWindow("Input", cv.WINDOW_AUTOSIZE)
|
||||
cv.namedWindow("Output", cv.WINDOW_AUTOSIZE)
|
||||
|
||||
cv.imshow("Input", src)
|
||||
t = round(time.time())
|
||||
|
||||
dst0 = sharpen(src)
|
||||
|
||||
t = (time.time() - t)
|
||||
print("Hand written function time passed in seconds: %s" % t)
|
||||
|
||||
cv.imshow("Output", dst0)
|
||||
cv.waitKey()
|
||||
|
||||
t = time.time()
|
||||
## [kern]
|
||||
kernel = np.array([[0, -1, 0],
|
||||
[-1, 5, -1],
|
||||
[0, -1, 0]], np.float32) # kernel should be floating point type
|
||||
## [kern]
|
||||
## [filter2D]
|
||||
dst1 = cv.filter2D(src, -1, kernel)
|
||||
# ddepth = -1, means destination image has depth same as input image
|
||||
## [filter2D]
|
||||
|
||||
t = (time.time() - t)
|
||||
print("Built-in filter2D time passed in seconds: %s" % t)
|
||||
|
||||
cv.imshow("Output", dst1)
|
||||
|
||||
cv.waitKey(0)
|
||||
cv.destroyAllWindows()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
@ -0,0 +1,92 @@
|
||||
from __future__ import division
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
# Snippet code for Operations with images tutorial (not intended to be run)
|
||||
|
||||
def load():
|
||||
# Input/Output
|
||||
filename = 'img.jpg'
|
||||
## [Load an image from a file]
|
||||
img = cv.imread(filename)
|
||||
## [Load an image from a file]
|
||||
|
||||
## [Load an image from a file in grayscale]
|
||||
img = cv.imread(filename, cv.IMREAD_GRAYSCALE)
|
||||
## [Load an image from a file in grayscale]
|
||||
|
||||
## [Save image]
|
||||
cv.imwrite(filename, img)
|
||||
## [Save image]
|
||||
|
||||
def access_pixel():
|
||||
# Accessing pixel intensity values
|
||||
img = np.empty((4,4,3), np.uint8)
|
||||
y = 0
|
||||
x = 0
|
||||
## [Pixel access 1]
|
||||
_intensity = img[y,x]
|
||||
## [Pixel access 1]
|
||||
|
||||
## [Pixel access 3]
|
||||
_blue = img[y,x,0]
|
||||
_green = img[y,x,1]
|
||||
_red = img[y,x,2]
|
||||
## [Pixel access 3]
|
||||
|
||||
## [Pixel access 5]
|
||||
img[y,x] = 128
|
||||
## [Pixel access 5]
|
||||
|
||||
def reference_counting():
|
||||
# Memory management and reference counting
|
||||
## [Reference counting 2]
|
||||
img = cv.imread('image.jpg')
|
||||
_img1 = np.copy(img)
|
||||
## [Reference counting 2]
|
||||
|
||||
## [Reference counting 3]
|
||||
img = cv.imread('image.jpg')
|
||||
_sobelx = cv.Sobel(img, cv.CV_32F, 1, 0)
|
||||
## [Reference counting 3]
|
||||
|
||||
def primitive_operations():
|
||||
img = np.empty((4,4,3), np.uint8)
|
||||
## [Set image to black]
|
||||
img[:] = 0
|
||||
## [Set image to black]
|
||||
|
||||
## [Select ROI]
|
||||
_smallImg = img[10:110,10:110]
|
||||
## [Select ROI]
|
||||
|
||||
## [BGR to Gray]
|
||||
img = cv.imread('image.jpg')
|
||||
_grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
## [BGR to Gray]
|
||||
|
||||
src = np.ones((4,4), np.uint8)
|
||||
## [Convert to CV_32F]
|
||||
_dst = src.astype(np.float32)
|
||||
## [Convert to CV_32F]
|
||||
|
||||
def visualize_images():
|
||||
## [imshow 1]
|
||||
img = cv.imread('image.jpg')
|
||||
cv.namedWindow('image', cv.WINDOW_AUTOSIZE)
|
||||
cv.imshow('image', img)
|
||||
cv.waitKey()
|
||||
## [imshow 1]
|
||||
|
||||
## [imshow 2]
|
||||
img = cv.imread('image.jpg')
|
||||
grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
sobelx = cv.Sobel(grey, cv.CV_32F, 1, 0)
|
||||
# find minimum and maximum intensities
|
||||
minVal = np.amin(sobelx)
|
||||
maxVal = np.amax(sobelx)
|
||||
draw = cv.convertScaleAbs(sobelx, alpha=255.0/(maxVal - minVal), beta=-minVal * 255.0/(maxVal - minVal))
|
||||
cv.namedWindow('image', cv.WINDOW_AUTOSIZE)
|
||||
cv.imshow('image', draw)
|
||||
cv.waitKey()
|
||||
## [imshow 2]
|
Reference in New Issue
Block a user