Opencv实现图片的边界填充和阈值处理
目录
图片的边界填充
指定颜色填充
BORDER_CONSTANT
- 格式:cv2.copyMakeBorder(a,t,b,l,r,borderType=BORDER_CONSTANT,value=(b,g,r))
- a:为图片变量
- t,b,l,r :为边界长度 ,顺序是上下左右
- borderType :可以设置边界类型 ,这里为BORDER_CONSTANT,指定颜色填充
- value :设置边界填充的颜色,色块顺序是BGR,为0-255的整数
代码展示:
python
a = cv2.imread('at1.png')
t,b,l,r = 40,40,40,40
a_cnostant = cv2.copyMakeBorder(a,t,b,l,r,borderType=cv2.BORDER_CONSTANT,value=(255,255,255))
cv2.imshow('a',a)
cv2.waitKey(0)
cv2.imshow('a_cnostant',a_cnostant)
cv2.waitKey(0)
运行结果:
镜面反射填充
- 格式:cv2.copyMakeBorder(a,t,b,l,r,borderType=BORDER_REFLECT)
borderType:- BORDER_REFLECT,镜面反射填充,交接处不删除
- BORDER_REFLECT101,镜面反射填充,交接处删除
代码展示:
python
a = cv2.imread('at1.png')
t,b,l,r = 70,70,70,70
a_reflect = cv2.copyMakeBorder(a,t,b,l,r,borderType=cv2.BORDER_REFLECT)
a_reflect101 = cv2.copyMakeBorder(a,t,b,l,r,borderType=cv2.BORDER_REFLECT101)
cv2.imshow('a_reflect',a_reflect)
cv2.waitKey(0)
cv2.imshow('a_reflect101',a_reflect101)
cv2.waitKey(0)
运行结果:
边界像素值替换
- 格式:cv2.copyMakeBorder(a,t,b,l,r,borderType=BORDER_REPLICATE)
borderType:- BORDER_REPLICATE,边界像素值替换,如aaaa,bbbbb类似,||||类似
- BORDER_WRAP,上下左右相互替换为边界
代码展示:
python
a = cv2.imread('at1.png')
t,b,l,r = 40,40,40,40
a_replicate = cv2.copyMakeBorder(a,t,b,l,r,borderType=cv2.BORDER_REPLICATE)
cv2.copyMakeBorder(a,t,b,l,r,borderType=cv2.BORDER_WRAP)
cv2.imshow('a_replicate',a_replicate)
cv2.waitKey(0)
cv2.imshow('a_wrap',a_wrap)
cv2.waitKey(0)
运行结果:
图片的阈值处理
基本格式
图片要进行阈值处理必须先转为灰度图,否则不能处理
基本格式:cv2.threshold(a,t,m,cv2.THRESH_XXXX)
a:图像变量
t:thresh数值,在0-255间,与像素值像比较
m:maxval数值,设置像素最大值,一般为255
cv2.THRESH_XXXX:XXXX决定处理类型
返回值:有两个,第一个是t(thresh数值),第二个是图像
基本类型
- BINARY
a的像素值> t(即图像的像素值 、thresh数值)时,取值为maxval,否则为0 - BINARY_INV
a的像素值> t 时,取值为maxval,否则为0 - TRUNC
a的像素值> t 时,取值为t(thresh值),否则为a原图像像素值 - TOZERO
a的像素值> t 时,a原图像像素值,否则为0 - TOZERO_INV
a的像素值> t 时,为0,否则为a原图像像素值
代码展示:
t 也可以自己调整修改 ,BINARY和BINARY_INV类型更突出
python
a = cv2.imread('at1.png',0)
r1,a_binary = cv2.threshold(a,150,255,cv2.THRESH_BINARY)
r2,a_binary_inv = cv2.threshold(a,150,255,cv2.THRESH_BINARY_INV)
r3,a_trunc = cv2.threshold(a,150,255,cv2.THRESH_TRUNC)
r4,a_tozero = cv2.threshold(a,150,255,cv2.THRESH_TOZERO)
r5,a_tozero_inv = cv2.threshold(a,150,255,cv2.THRESH_TOZERO_INV)
cv2.imshow('a',a)
cv2.waitKey(0)
cv2.imshow('a_binary',a_binary)
cv2.waitKey(0)
cv2.imshow('a_binary_inv',a_binary_inv)
cv2.waitKey(0)
cv2.imshow('a_trunc',a_trunc)
cv2.waitKey(0)
cv2.imshow('a_tozero',a_tozero)
cv2.waitKey(0)
cv2.imshow('a_tozero_inv',a_tozero_inv)
cv2.waitKey(0)
print(r1,r2,r3,r4,r5)
cv2.destroyAllWindows()
运行结果: