关于一些基础的opencv图像操作函数的脑图
① 二值化函数简单应用
python
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('12.png', cv2.IMREAD_GRAYSCALE)
img1 = cv2.imread('12.png', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('12.png', cv2.IMREAD_GRAYSCALE)
ret, img1 = cv2.threshold(img1, 127, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
ret2, img2 = cv2.threshold(img2, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('img', img)
cv2.imshow('img1', img1)
cv2.imshow('img2', img2)
cv2.waitKey(0)
②自适应二值化函数简单应用
python
import cv2
img = cv2.imread('1.png', cv2.IMREAD_GRAYSCALE)
img_adaptive_binary = cv2.adaptiveThreshold(img,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
37,
5
)
cv2.imshow('img', img)
cv2.imshow('img_adaptive_binary', img_adaptive_binary)
cv2.waitKey(0)
③腐蚀函数简单应用
python
import cv2
img_binary = cv2.imread('2.png')
ret = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9))
img_erode = cv2.erode(img_binary, ret)
cv2.imshow('img', img_binary)
cv2.imshow('img_erode', img_erode)
cv2.waitKey(0)
④膨胀函数简单应用
python
import cv2
# 读取一张彩色图
img = cv2.imread("1.png")
# 转换成灰度图
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 转换成二值化图
img_binary = cv2.adaptiveThreshold(img_gray,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,
7,
5)
# 进行腐蚀和膨胀操作
# 1、创建结构化元素 / 核
kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
# 2、调用腐蚀函数
img_erode = cv2.erode(img_binary, kernal)
# 3、调用膨胀函数
img_erode_dilate = cv2.dilate(img_erode, kernal)
cv2.imshow('image_binary', img_binary)
cv2.imshow('image_erode', img_erode)
cv2.imshow('image_erode_dilate', img_erode_dilate)
cv2.waitKey(0)
⑤仿射变换函数简单应用
python
import cv2
img = cv2.imread('5.png')
m = cv2.getRotationMatrix2D((img.shape[1] / 2, img.shape[0] / 2), 45, 0.5)
img_new = cv2.warpAffine(img, m, (img.shape[0], img.shape[1]), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
cv2.imshow('img',img)
cv2.imshow('img_new',img_new)
cv2.waitKey(0)
⑥透视变换函数简单应用
python
import cv2
import numpy as np
img = cv2.imread("6.png")
#获取透视变换矩阵
#原图中的4个点
points1 = np.array([[223, 118], [680, 176], [139, 380], [654, 451]],dtype=np.float32)
#目标中的4个点
points2 = np.array([[0, 0], [img.shape[1], 0], [0, img.shape[0]], [img.shape[1], img.shape[0]]],dtype=np.float32)
M = cv2.getPerspectiveTransform(points1, points2)
img_warp=cv2.warpPerspective(img,M,(img.shape[1],img.shape[0]))
cv2.imshow("img",img)
cv2.imshow('img_warp', img_warp)
cv2.waitKey(0)
原图: