安装opencv,前面有说到,直接用命令:
pip install opencv-python
新建图片显示的窗口,设置图片宽和高,以及四周边框的宽度:
# 读取源图片
img = r'logo.png'
image = cv2.imread(img)
# 图片宽高 W H
W, H = 256, 256
image = cv2.resize(image, (W, H))
# 新建图片显示的窗口
window_name = '中文图片'
# 设置边框宽度
top, bottom, left, right = 10, 5, 10, 5
设置边框的颜色:
# rgb颜色值 0~255
R, B, G = 0, 255, 0
绘制边框:
# 绘制边框默认BORDER_CONSTANT
image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(R, B, G))
image1 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_DEFAULT)
image2 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_ISOLATED)
image3 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_REFLECT)
image4 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_REFLECT101)
image5 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_REPLICATE)
# image6 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_TRANSPARENT)
image7 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_WRAP)
borderType:扩充边缘的类型,就是外插的类型,OpenCV中给出以下几种方式
BORDER_REPLICATE 重复: 就是对边界像素进行复制
BORDER_REFLECT 反射:对感兴趣的图像中的像素在两边进行复制例如:fedcba|abcdefgh|hgfedcb 反射
BORDER_REFLECT_101 反射101: 例子:gfedcb|abcdefgh|gfedcba
BORDER_WRAP 外包装:cdefgh|abcdefgh|abcdefg
BORDER_CONSTANT 常量复制:例子:iiiiii|abcdefgh|iiiiiii
BORDER_REPLICATE:复制法,也就是复制最边缘像素。
BORDER_REFLECT_101:对称法,也就是以最边缘像素为轴,对称。
显示加载好边框的图片在窗口中:
# 加完边框后的图片显示在窗口中
cv2.imshow(zh_ch(window_name), image)
运行结果:
完整代码:
# -*- coding: UTF8 -*-
import cv2
# 解决imshow中文乱码问题
def zh_ch(string):
return string.encode("gbk").decode(errors="ignore")
# 读取源图片
img = r'logo.png'
image = cv2.imread(img)
# 图片宽高 W H
W, H = 256, 256
image = cv2.resize(image, (W, H))
# 新建图片显示的窗口
window_name = '中文图片'
# 设置边框宽度
top, bottom, left, right = 10, 5, 10, 5
# rgb颜色值 0~255
R, B, G = 0, 255, 0
# 绘制边框默认BORDER_CONSTANT
image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(R, B, G))
image1 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_DEFAULT)
image2 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_ISOLATED)
image3 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_REFLECT)
image4 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_REFLECT101)
image5 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_REPLICATE)
# image6 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_TRANSPARENT)
image7 = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_WRAP)
# 加完边框后的图片显示在窗口中
cv2.imshow(zh_ch(window_name), image)
# 让输出窗口不自动关闭,等待输入按键关闭ss
cv2.waitKey()
cv2.isshow窗口标题中文会出现乱码,解决办法是:
# 解决imshow中文乱码问题
def zh_ch(string):
return string.encode("gbk").decode(errors="ignore")