学习OpenCV+Python

文章目录

      • 一.学习资料
      • 二.Section1
        • 1.basic_functions.py
        • 2.contours.py
        • 3.draw.py
        • 4.read.py
        • 5.thresh.py
        • 6.transformations.py
      • 三.Section2
        • 1.bitwise.py
        • 2.blurring.py
        • 3.colour_spaces.py
        • 4.gradients.py
        • 5.histogram.py
        • 6.masking.py
        • 7.rescale_resize.py
        • 8.splitmerge.py
      • 四.总结

一.学习资料

链接:https://pan.baidu.com/s/1lU7vIkTxB14YBFAK-IRtuQ
提取码:1234

二.Section1

1.basic_functions.py

# 从指定路径读取图片
img = cv.imread('../Resources/Photos/park.jpg')
cv.imshow('Park', img)

在这里插入图片描述

# 将图片转成灰度
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

学习OpenCV+Python_第1张图片

# 利用高斯滤波对图片进行模糊处理
blur = cv.GaussianBlur(img, (7,7), cv.BORDER_DEFAULT)
cv.imshow('Blur', blur)

学习OpenCV+Python_第2张图片

# 边缘检测
canny = cv.Canny(blur, 125, 175)
cv.imshow('Canny Edges', canny)

学习OpenCV+Python_第3张图片

# 膨胀
dilated = cv.dilate(canny, (7,7), iterations=3)
cv.imshow('Dilated', dilated)

学习OpenCV+Python_第4张图片

# 腐蚀
eroded = cv.erode(dilated, (7,7), iterations=3)
cv.imshow('Eroded', eroded)

在这里插入图片描述

# 调整图片尺寸
resized = cv.resize(img, (500,500), interpolation=cv.INTER_CUBIC)
cv.imshow('Resized', resized)

学习OpenCV+Python_第5张图片

# 裁剪
cropped = img[50:200, 200:400]
cv.imshow('Cropped', cropped)

学习OpenCV+Python_第6张图片

2.contours.py

#从指定路径读取图片
img = cv.imread('../Resources/Photos/cats.jpg')
cv.imshow('Cats', img)

学习OpenCV+Python_第7张图片

#显示一个blank空白窗口
blank = np.zeros(img.shape, dtype='uint8')
cv.imshow('Blank', blank)

学习OpenCV+Python_第8张图片

#转灰度图
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

学习OpenCV+Python_第9张图片

#模糊
blur = cv.GaussianBlur(gray, (5,5), cv.BORDER_DEFAULT)
cv.imshow('Blur', blur)

学习OpenCV+Python_第10张图片

#边缘检测
canny = cv.Canny(blur, 125, 175)
cv.imshow('Canny Edges', canny)

学习OpenCV+Python_第11张图片

contours, hierarchies = cv.findContours(canny, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
print(f'{len(contours)} contour(s) found!')

cv.drawContours(blank, contours, -1, (0,0,255), 1)
cv.imshow('Contours Drawn', blank)

学习OpenCV+Python_第12张图片

3.draw.py

zeros()函数

用法:zeros(shape, dtype=float, order=‘C’)

返回:返回来一个给定形状和类型的用0填充的数组;

参数:shape:形状

dtype:数据类型,可选参数,默认numpy.float64

dtype类型:

t ,位域,如t4代表4位

b,布尔值,true or false

i,整数,如i8(64位)

u,无符号整数,u8(64位)

f,浮点数,f8(64位)

c,浮点负数,

o,对象,

s,a,字符串,s24

u,unicode,u24

order:可选参数,c代表与c语言类似,行优先;F代表列优先

#显示一个blank空白窗口
blank = np.zeros((500,500,3), dtype='uint8')
cv.imshow('Blank', blank)

学习OpenCV+Python_第13张图片

# 1. Paint the image a certain colour
blank[200:300, 300:400] = 0,0,255
cv.imshow('Green', blank)

学习OpenCV+Python_第14张图片

# 2. Draw a Rectangle
cv.rectangle(blank, (0,0), (blank.shape[1]//2, blank.shape[0]//2), (0,255,0), thickness=-1)
cv.imshow('Rectangle', blank)

学习OpenCV+Python_第15张图片

# 3. Draw A circle
cv.circle(blank, (blank.shape[1]//2, blank.shape[0]//2), 40, (0,0,255), thickness=-1)
cv.imshow('Circle', blank)

学习OpenCV+Python_第16张图片

# 4. Draw a line
cv.line(blank, (100,250), (300,400), (255,255,255), thickness=3)
cv.imshow('Line', blank)

学习OpenCV+Python_第17张图片

# 5. Write text
cv.putText(blank, 'Hello, my name is Jason!!!', (0,225), cv.FONT_HERSHEY_TRIPLEX, 1.0, (0,255,0), 2)
cv.imshow('Text', blank)

学习OpenCV+Python_第18张图片

4.read.py

img = cv.imread('../Resources/Photos/cats.jpg')
cv.imshow('Cats', img)

学习OpenCV+Python_第19张图片

# Reading Videos
capture = cv.VideoCapture('../Resources/Videos/dog.mp4')

while True:
    isTrue, frame = capture.read()
    
    # if cv.waitKey(20) & 0xFF==ord('d'):
    # This is the preferred way - if `isTrue` is false (the frame could 
    # not be read, or we're at the end of the video), we immediately
    # break from the loop. 
    if isTrue:    
        cv.imshow('Video', frame)
        if cv.waitKey(20) & 0xFF==ord('d'):
            break            
    else:
        break

capture.release()
cv.destroyAllWindows()

5.thresh.py

img = cv.imread('../Resources/Photos/cats.jpg')
cv.imshow('Cats', img)

学习OpenCV+Python_第20张图片

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

学习OpenCV+Python_第21张图片

# Simple Thresholding
threshold, thresh = cv.threshold(gray, 150, 255, cv.THRESH_BINARY )
cv.imshow('Simple Thresholded', thresh)

学习OpenCV+Python_第22张图片

threshold, thresh_inv = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV )
cv.imshow('Simple Thresholded Inverse', thresh_inv)

学习OpenCV+Python_第23张图片

# Adaptive Thresholding
adaptive_thresh = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, 11, 9)
cv.imshow('Adaptive Thresholding', adaptive_thresh)

学习OpenCV+Python_第24张图片

6.transformations.py

img = cv.imread('../Resources/Photos/park.jpg')
cv.imshow('Park', img)

学习OpenCV+Python_第25张图片

# Translation
def translate(img, x, y):
    transMat = np.float32([[1,0,x],[0,1,y]])
    dimensions = (img.shape[1], img.shape[0])
    return cv.warpAffine(img, transMat, dimensions)

# -x --> Left
# -y --> Up
# x --> Right
# y --> Down

translated = translate(img, -100, 100)
cv.imshow('Translated', translated)

学习OpenCV+Python_第26张图片

# Rotation
def rotate(img, angle, rotPoint=None):
    (height,width) = img.shape[:2]

    if rotPoint is None:
        rotPoint = (width//2,height//2)
    
    rotMat = cv.getRotationMatrix2D(rotPoint, angle, 1.0)
    dimensions = (width,height)

    return cv.warpAffine(img, rotMat, dimensions)

rotated = rotate(img, -45)
cv.imshow('Rotated', rotated)

rotated_rotated = rotate(img, -90)
cv.imshow('Rotated Rotated', rotated_rotated)

学习OpenCV+Python_第27张图片

学习OpenCV+Python_第28张图片

# Resizing
resized = cv.resize(img, (500,500), interpolation=cv.INTER_CUBIC)
cv.imshow('Resized', resized)

学习OpenCV+Python_第29张图片

# Flipping
flip = cv.flip(img, -1)
cv.imshow('Flip', flip)

学习OpenCV+Python_第30张图片

# Cropping
cropped = img[200:400, 300:400]
cv.imshow('Cropped', cropped)

学习OpenCV+Python_第31张图片

三.Section2

1.bitwise.py

blank = np.zeros((400,400), dtype='uint8')

rectangle = cv.rectangle(blank.copy(), (30,30), (370,370), 255, -1)
circle = cv.circle(blank.copy(), (200,200), 200, 255, -1)

cv.imshow('Rectangle', rectangle)
cv.imshow('Circle', circle)

学习OpenCV+Python_第32张图片

学习OpenCV+Python_第33张图片

# bitwise AND --> intersecting regions
bitwise_and = cv.bitwise_and(rectangle, circle)
cv.imshow('Bitwise AND', bitwise_and)

学习OpenCV+Python_第34张图片

# bitwise OR --> non-intersecting and intersecting regions
bitwise_or = cv.bitwise_or(rectangle, circle)
cv.imshow('Bitwise OR', bitwise_or)

学习OpenCV+Python_第35张图片

# bitwise XOR --> non-intersecting regions
bitwise_xor = cv.bitwise_xor(rectangle, circle)
cv.imshow('Bitwise XOR', bitwise_xor)

学习OpenCV+Python_第36张图片

# bitwise NOT
bitwise_not = cv.bitwise_not(circle)
cv.imshow('Circle NOT', bitwise_not)

学习OpenCV+Python_第37张图片

2.blurring.py

img = cv.imread('../Resources/Photos/cats.jpg')
cv.imshow('Cats', img)

学习OpenCV+Python_第38张图片

# Averaging
average = cv.blur(img, (3,3))
cv.imshow('Average Blur', average)

学习OpenCV+Python_第39张图片

# Gaussian Blur
gauss = cv.GaussianBlur(img, (3,3), 0)
cv.imshow('Gaussian Blur', gauss)

学习OpenCV+Python_第40张图片

# Median Blur
median = cv.medianBlur(img, 3)
cv.imshow('Median Blur', median)

学习OpenCV+Python_第41张图片

# Bilateral
bilateral = cv.bilateralFilter(img, 10, 35, 25)
cv.imshow('Bilateral', bilateral)

学习OpenCV+Python_第42张图片

3.colour_spaces.py

img = cv.imread('../Resources/Photos/park.jpg')
cv.imshow('Park', img)

学习OpenCV+Python_第43张图片

# BGR to Grayscale
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

学习OpenCV+Python_第44张图片

# BGR to HSV
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
cv.imshow('HSV', hsv)

学习OpenCV+Python_第45张图片

# BGR to L*a*b
lab = cv.cvtColor(img, cv.COLOR_BGR2LAB)
cv.imshow('LAB', lab)

学习OpenCV+Python_第46张图片

# BGR to RGB
rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
cv.imshow('RGB', rgb)

学习OpenCV+Python_第47张图片

# HSV to BGR
lab_bgr = cv.cvtColor(lab, cv.COLOR_LAB2BGR)
cv.imshow('LAB --> BGR', lab_bgr)

学习OpenCV+Python_第48张图片

4.gradients.py

img = cv.imread('../Resources/Photos/park.jpg')
cv.imshow('Park', img)

学习OpenCV+Python_第49张图片

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

学习OpenCV+Python_第50张图片

# Laplacian
lap = cv.Laplacian(gray, cv.CV_64F)
lap = np.uint8(np.absolute(lap))
cv.imshow('Laplacian', lap)

学习OpenCV+Python_第51张图片

# Sobel算子 
sobelx = cv.Sobel(gray, cv.CV_64F, 1, 0)
sobely = cv.Sobel(gray, cv.CV_64F, 0, 1)
combined_sobel = cv.bitwise_or(sobelx, sobely)

cv.imshow('Sobel X', sobelx)
cv.imshow('Sobel Y', sobely)
cv.imshow('Combined Sobel', combined_sobel)

学习OpenCV+Python_第52张图片

学习OpenCV+Python_第53张图片

学习OpenCV+Python_第54张图片

canny = cv.Canny(gray, 150, 175)
cv.imshow('Canny', canny)

学习OpenCV+Python_第55张图片

5.histogram.py

img = cv.imread('../Resources/Photos/cats.jpg')
cv.imshow('Cats', img)

学习OpenCV+Python_第56张图片

blank = np.zeros(img.shape[:2], dtype='uint8')

# gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# cv.imshow('Gray', gray)

mask = cv.circle(blank, (img.shape[1]//2,img.shape[0]//2), 100, 255, -1)

masked = cv.bitwise_and(img,img,mask=mask)
cv.imshow('Mask', masked)

学习OpenCV+Python_第57张图片

# Colour Histogram

plt.figure()
plt.title('Colour Histogram')
plt.xlabel('Bins')
plt.ylabel('# of pixels')
colors = ('b', 'g', 'r')
for i,col in enumerate(colors):
    hist = cv.calcHist([img], [i], mask, [256], [0,256])
    plt.plot(hist, color=col)
    plt.xlim([0,256])

plt.show()

学习OpenCV+Python_第58张图片

6.masking.py

img = cv.imread('../Resources/Photos/cats 2.jpg')
cv.imshow('Cats', img)

在这里插入图片描述

blank = np.zeros(img.shape[:2], dtype='uint8')
cv.imshow('Blank Image', blank)

学习OpenCV+Python_第59张图片

circle = cv.circle(blank.copy(), (img.shape[1]//2 + 45,img.shape[0]//2), 100, 255, -1)

rectangle = cv.rectangle(blank.copy(), (30,30), (370,370), 255, -1)

weird_shape = cv.bitwise_and(circle,rectangle)
cv.imshow('Weird Shape', weird_shape)

学习OpenCV+Python_第60张图片

masked = cv.bitwise_and(img,img,mask=weird_shape)
cv.imshow('Weird Shaped Masked Image', masked)

学习OpenCV+Python_第61张图片

7.rescale_resize.py

缩放

def rescaleFrame(frame, scale=0.75):
    # Images, Videos and Live Video
    width = int(frame.shape[1] * scale)
    height = int(frame.shape[0] * scale)

    dimensions = (width,height)

    return cv.resize(frame, dimensions, interpolation=cv.INTER_AREA)

改变视频宽度和高度

def changeRes(width,height):
    # Live video
    capture.set(3,width)
    capture.set(4,height)
# Reading Videos
capture = cv.VideoCapture('../Resources/Videos/dog.mp4')

while True:
    isTrue, frame = capture.read()

    frame_resized = rescaleFrame(frame, scale=.2)
    #原视频
    cv.imshow('Video', frame)
    #处理后视频
    cv.imshow('Video Resized', frame_resized)

    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

8.splitmerge.py

img = cv.imread('../Resources/Photos/park.jpg')
cv.imshow('Park', img)

学习OpenCV+Python_第62张图片

blank = np.zeros(img.shape[:2], dtype='uint8')

b,g,r = cv.split(img)

blue = cv.merge([b,blank,blank])
green = cv.merge([blank,g,blank])
red = cv.merge([blank,blank,r])

#只保留一个通道
cv.imshow('Blue', blue)
cv.imshow('Green', green)
cv.imshow('Red', red)

print(img.shape)
print(b.shape)
print(g.shape)
print(r.shape)

学习OpenCV+Python_第63张图片

学习OpenCV+Python_第64张图片

学习OpenCV+Python_第65张图片

#通道合并
merged = cv.merge([b,g,r])
cv.imshow('Merged Image', merged)

学习OpenCV+Python_第66张图片

四.总结

这些函数基本上都是现成的,重点理解图片处理的基本步骤。

你可能感兴趣的:(人工智能与机器学习,opencv,python,计算机视觉)