(Python+OpenCV)彩色图片转二值图片

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 11:23:04 2020

@author: 94456
"""


import sys
import cv2 as cv


#显示Python和OpenCV版本
print('Python版本为:Python',sys.version_info.major)
print('OpenCV版本为:',cv.__version__)


#图片路径
#(应避免有中文)
image_path=r'C:\Users\94456\Desktop\test2020_09_03\picture\cat.jpg'


#读取图片
#类型:numpy.ndarray
image=cv.imread(image_path)


#显示原图
cv.imshow('cat',image)


#原图转为灰度图
image_gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)
#显示灰度图
cv.imshow('cat_gray',image_gray)


#OpenCV:threshold
#THRESH_BINARY:大于thresh变maxval,小于等于thresh变0
#THRESH_BINARY_INV:大于thresh变0,小于等于thresh变maxval
#THRESH_TRUNC:大于thresh变thresh,小于等于thresh不变
#THRESH_TOZERO:大于thresh不变,小于等于thresh置0
#THRESH_TOZERO_INV:大于thresh置0,小于等于thresh不变
ret,image_thresh_binary=cv.threshold(image_gray,128,255,cv.THRESH_BINARY)
#返回值:
#ret:与参数thresh一致
#结果图像


#显示二值化图片
cv.imshow('cat_thresh_binary',image_thresh_binary)


#将灰度图片进行另一种二值化
ret,image_thresh_binary_inv=cv.threshold(image_gray,128,255,cv.THRESH_BINARY_INV)
#显示另一种二值化的图片
cv.imshow('cat_thresh_binary_inv',image_thresh_binary_inv)


cv.waitKey(0)
cv.destroyAllWindows()

 

你可能感兴趣的:(计算机视觉,opencv,python,计算机视觉)