# python图像处理代码块
- 这里一一列出工作中总结一些简单代码块
- 关于图像处理的
- 比如旋转缩放等等 。。。。
# 图片等比例旋转
# 以点img中心为中心,旋转angle度,兼容mask
def rotateImg(img, angle, rotPoint=None):
height,width = img.shape[:2]
if rotPoint is None:
rotPoint = width //2, height//2
M = cv2.getRotationMatrix2D(rotPoint, -angle,1.0)
dimension = (width,height)
# print(img.shape)
return cv2.warpAffine(img, M, dimension)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 旋转一个坐标点
# 以点img中心为中心,旋转angle度,兼容mask
def rotateImg(img, angle, rotPoint=None):
height,width = img.shape[:2]
if rotPoint is None:
rotPoint = width //2, height//2
M = cv2.getRotationMatrix2D(rotPoint, -angle,1.0)
dimension = (width,height)
# print(img.shape)
return cv2.warpAffine(img, M, dimension)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 图片转base64
def image_to_base64(image_np):
image = cv2.imencode('.png', image_np)[1]
image_code = str(base64.b64encode(image))[2:-1]
return image_code
1
2
3
4
2
3
4
# 在图片上画圆、矩形、点
- 画矩形
leftTop = (0,0) # 必须为元组
rightBottom = (12,12) # 必须为元组
color = (255,255,255) # 必须为元组
thiness = -1 # 整数,-1代表实心填充
cv2.rectangle(img, leftTop, rightBottom, color, thiness)
1
2
3
4
5
2
3
4
5
- 画圆
cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]])
1
- 画点(当参数 chinkness = -1 是就是点了)
cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]])
1
# 图片二值化求轮廓
_, mask = cv2.threshold(mask, 100, 255, cv2.THRESH_BINARY)
cs, hs = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
1
2
2
# opencv-python 中文路径图片读取和保存
- 如果图片的存储路径存在中文
- 保险起见建议使用 一下方法代替
cv2.imread() cv2.imwrite()
def imread(im_name):
return cv2.imdecode(np.fromfile(im_name,dtype=np.uint8),-1)
def imwrite(savePath, img):
cv2.imencode(f'{Path(savePath).suffix}', img)[1].tofile(savePath)
1
2
3
4
5
2
3
4
5
# 求mask的最大内接圆
- 先求mask的轮廓(注意使用求轮廓方法获取的是轮廓的列表)
- 这里求一张图片里面最大轮廓
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
areas = ([cv2.contourArea(contour) for contour in contours])
maxId = np.argmax(areas)
maxCountour = contours[maxId] # 最大轮廓
# 开始求这个轮廓的最大内接圆
# 最大内接圆和最小外切圆计算宽高
raw_dist = np.empty(mask.shape, dtype=np.float32)
for i in range(mask.shape[0]):
for j in range(mask.shape[1]):
raw_dist[i,j] = cv2.pointPolygonTest(maxCountour, (j,i), True)
_, maxVal, _, _ = cv2.minMaxLoc(raw_dist)
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12