整理图像处理相关的代码和问题,方便查阅
读取图片
# 法1
import cv2
image_cv = cv2.imread('0.jpg') # numpy.ndarray
# 法2
from PIL import Image
image_pil = Image.open('0.jpg') # PIL图片格式
# 法1法2的结果互相转换
image_pil = Image.fromarray(image_cv) # 1->2
image_numpy = np.array(image_pil) # 2->1
# 法3
import skimage.io as io
image = io.imread('0.jpg') # 直接为RGB
io.imshow(image)
图像变换
# 更改颜色通道
# OpenCV使用BGR约定存储彩色图像,matplotlib使用RGB约定。
img_color = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32) # 同时修改数据类型
# PIL.Image.convert
img_1 = img.convert('1')
img_L = img.convert('L')
img_RGB = img.convert('RGB')
# 更改大小
img_size = cv2.resize(img_rgb, (self.width, self.height), cv2.INTER_AREA)
# 变换维度
torch.Tensor.permute, eg:x.permute(2, 0, 1) # 更改顺序
numpy.transpose, eg:x.transpose(2, 0, 1) # 更改顺序
torch.squeeze() # 降维
torch.unsqueeze() # 增维
numpy.newaxis, eg:x[:,np.newaxis,:] # 增维
numpy.squeeze() # 降维
图像处理
# 高斯模糊
image_gauss = cv2.GaussianBlur(image, (3, 3), 0)
# 图片灰度化
image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 边缘算子
image_canny = cv2.Canny(image,200,250)
# 二值化
ret, image_two = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU)
# 形态学(腐蚀,膨胀,开操作,闭操作)
# 闭操作
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (35, 8))
image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernelX)
# 膨胀腐蚀
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 18))
image = cv2.dilate(image, kernelX)
image = cv2.erode(image, kernelX)
image = cv2.erode(image, kernelY)
image = cv2.dilate(image, kernelY)
# 中值滤波
image = cv2.medianBlur(image, 15)
绘制
# 展示图像
fig,ax = plt.subplots(1)
fig.set_size_inches(18.5, 10.5)
ax.imshow(img.permute(1, 2, 0)) # 将通道C换到第三位
# 在图像上绘制矩形
rect = patches.Rectangle((xmin,ymin),(xmax-xmin),(ymax-ymin),linewidth=2,edgecolor='r',facecolor='none')
ax.add_patch(rect)
# 添加文字
ax.text(xmin, ymin, f"{label}", horizontalalignment='center', verticalalignment='center',fontsize=20,color='b')
plt.savefig(fullPath) # 若要保存,得在show()之前
plt.show()
常见问题
1)图像数据类型是np.float32还是np.uint8
2)图像维度数量,灰度图和RGB,BGR
3)C,W,H相对位置
4)图像处理的参数
5)是否被转置