图片的读取和保存
import cv2
# 图像读取
img = cv2.imread(data_path)
# 图像保存
cv2.imwrite(save_path, img)
# 目录中有中文时
# 图像读取
img = cv2.imdecode(np.fromfile(data_path, dtype=np.uint8), cv2.IMREAD_COLOR)
# 图像保存
cv2.imencode('.jpg', img)[1].tofile(save_path)
边界绘制
注意: 绘制边界时,图像一定是二值图
'''
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
'''
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 寻找轮廓
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
直方图均衡化
'''
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
clahe_img = clahe.apply(img_gray)
'''
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
clahe_img = clahe.apply(img_gray)
绘制正方形
'''
cv2.rectangle(img, top, down, (0, 255, 0), 2)
'''
import cv2
# 图像读取
img = cv2.imread(data_path)
# 矩形左上点和右下点坐标
top = (x1, y1)
down =(x2, y2)
# 绘制正方形
cv2.rectangle(img, top, down, (0, 255, 0), 2)
拟合最小外接矩形,椭圆
'''
# 最小外接矩形
rect = cv2.minAreaRect(contour)
'''
import cv2
# Load an image and convert it to grayscale
img = cv2.imread('image.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
'''
# 椭圆
ellipse = cv2.fitEllipse(contour)
ellipse = cv2.minEclosingCircle(contour)
'''
import cv2
img = cv2.imread('image.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if contour.shape[0] >= 5:
ellipse = cv2.fitEllipse(contour)
cv2.ellipse(img, ellipse, (0, 255, 0), 2)
在图上绘制文字
'''
cv2.putText(img, text, down, cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
'''
import cv2
img = cv2.imread('image.jpg')
# 定义要绘制的文字和位置
text = "Hello, World!"
down = (50, 200)
color = (0, 255, 0)
# 在图像上绘制文字
cv2.putText(img, text, down, cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
生成随机颜色
import random
random.seed(1)
color = (random.randrange(40, 255, 50),
random.randrange(50, 255, 50),
random.randrange(50, 255, 50))
调整亮度对比度
# 定义亮度和对比度调整系数
alpha = 1.5 # 对比度调整系数
beta = 50 # 亮度调整系数
# 调整图像亮度和对比度
adjusted = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)