代码实现
import matplotlib.pyplot as plt
import cv2
import numpy as np
img = cv2.imread("./demo.jpg")
"""
图像padding为正方形
"""
def square_img(img_cv):
# 获取图像的宽高
img_h,img_w = img_cv.shape[0:2]
# 计算padding值并将图像padding为正方形
padw,padh = 0,0
if img_h>img_w:
padw = (img_h - img_w) // 2
img_pad = np.pad(img_cv,((0,0),(padw,padw),(0,0)),'constant',constant_values=0)
elif img_w>img_h:
padh = (img_w - img_h) // 2
img_pad = np.pad(img_cv,((padh,padh),(0,0),(0,0)), 'constant', constant_values=0)
return img_pad
"""
在图像上绘制网格
核心函数
cv2.line(img, (start_x, start_y), (end_x, end_y), (255, 0, 0), 1, 1)
"""
def draw_grid(img,grid_x,grid_y,line_width=5):
img_x,img_y = img.shape[:2]
# 绘平行y方向的直线
dx = int(img_x/grid_x)
for i in range(0,img_x,dx):
cv2.line(img, (i, 0), (i, img_y), (255, 0, 0), line_width)
# 绘平行x方向的直线
dy = int(img_y/grid_y)
for i in range(0,img_x,dx):
cv2.line(img, (0, i), (img_x, i), (255, 0, 0), line_width)
return img
img = square_img(img)
img = draw_grid(img,20,20) # 20,20为网格的shape
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.figure(dpi=200)
plt.xticks([])
plt.yticks([])
plt.imshow(img)
plt.show()
调用效果
代码参数需要稍作修改才能得到如下全部效果
评论 (0)