python-opencv 培训课程笔记(2)

python-opencv 培训课程笔记(2)

1.图像格式转换

先看一下cvtColor函数的例子

#默认加载彩图
path=r'D:\learn\photo\cv\cat.jpg'

# imread(path,way)
#way=0 灰度图。way=1 彩图
#默认彩图
img=cv2.imread(path)
img_dog=cv2.imread(path_dog)
#图片格式的转化
#cv2.COLOR_BGR2GRAY

#cv2.COLOR_BGR2RGB
#cv2.COLOR_BGR2HSV,HSV-色调、饱和度、亮度

img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

img_hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

img_rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

print(img.shape)
def cv_show(name,img):
    cv2.imshow(name,img)
    #cv2.waitKey(0),接收0,表示窗口暂停
    cv2.waitKey(0)
    #销毁所有窗口
    cv2.destroyAllWindows()
cv_show('hsv',img_hsv)  
cv_show('rgb',img_rgb)  
cv_show('hsv',img)  

cvtColor函数第二个参数可以选择转换格式:
#cv2.COLOR_BGR2GRAY 将BGR转换为灰度图

#cv2.COLOR_BGR2RGB 将BGR转换为RGB格式
#cv2.COLOR_BGR2HSV,HSV-色调、饱和度、亮度 将BGR进行HSV处理
下面我们看下效果:
python-opencv 培训课程笔记(2)_第1张图片

python-opencv 培训课程笔记(2)_第2张图片
python-opencv 培训课程笔记(2)_第3张图片

注意,opencv读取数据三通道的顺序是GBR
matplotlib顺序是读取数据三通道的顺序是RGB

2.图像阈值转化



#图像阈值
#二值化 
#THRESH_BINARY超过127 取 255否则取0
#THRESH_BINARY_INV  THRESH_BINARY的反转
#THRESH_TRUNC  超过127 取 255否则不变
#THRESH_TOZERO  超过127 取 不变否则取0

#THRESH_TOZERO_INV THRESH_TOZERO的反转



ret,dst1=cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)

ret,dst2=cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY_INV)
ret,dst3=cv2.threshold(img_gray,127,255,cv2.THRESH_TRUNC)

ret,dst4=cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO)

ret,dst5=cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO_INV)

images=[dst1,dst2,dst3,dst4,dst4]
titles=['Original','THRESH_BINARY','THRESH_BINARY_INV','THRESH_TRUNC','THRESH_TOZERO','THRESH_TOZERO_INV']
for i in range(5):
    plt.subplot(2,3,i+1)
    plt.imshow(images[i],'gray')
    plt.title(titles[i])


plt.show()

cv2.threshold第二个参数解释如下
#THRESH_BINARY超过127 取 255否则取0
#THRESH_BINARY_INV THRESH_BINARY的反转
#THRESH_TRUNC 超过127 取 255否则不变
#THRESH_TOZERO 超过127 取 不变否则取0
#THRESH_TOZERO_INV THRESH_TOZERO的反转
看一下效果:
python-opencv 培训课程笔记(2)_第4张图片

你可能感兴趣的:(python,人工智能,opencv,python,笔记)