resize函数c++
python-opencv利⽤阈值函数将灰度图⼆值化
import cv2 as cv
img = cv.imread('./shangyi.jpg',cv.IMREAD_COLOR)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#固定阈值⼿动决定thresh⼤⼩
#src:灰度图资源 thresh:阈值 maxval:像素最⼤值 type:像素值分配⽅式
#将灰度图中的灰度值进⾏⼆值化变换,变换⽅式由type决定
# eq:cv.THRESH_BINARY表⽰⼤于thresh的灰度值会转为maxval,⼩于thresh的灰度值会转为0
ret,thresh1 = cv.threshold(gray,127,255,cv.THRESH_BINARY)
ret,thresh2 = cv.threshold(gray,127,255,cv.THRESH_BINARY_INV)
ret,thresh3 = cv.threshold(gray,127,255,cv.THRESH_TRUNC)
ret,thresh4 = cv.threshold(gray,127,255,cv.THRESH_TOZERO)
ret,thresh5 = cv.threshold(gray,127,255,cv.THRESH_TOZERO_INV)
#不同类型的转换⽅式对⽐
cv.namedWindow('img',cv.WINDOW_NORMAL)
cv.imshow('img',thresh1)
cv.waitKey(0)
cv.imshow('img',thresh2)
cv.waitKey(0)
cv.imshow('img',thresh3)
cv.waitKey(0)
cv.imshow('img',thresh4)
cv.waitKey(0)
cv.imshow('img',thresh5)
cv.waitKey(0)
cv.destroyAllWindows()
#⾃适应阈值 thresh由⾃适应⽅法动态得出,⼀张灰度图中可以分成多个区域阈值
#src:灰度图资源 maxval:像素最⼤值 adaptiveMethod:⾃适应⽅式 thresholdType:像素值分配⽅式 blockSize:区域块⼤⼩(必须是⼤于1的奇数) C:常数C(偏移量,⽤于矫正阈值)
#eq:cv.ADAPTIVE_THRESH_GAUSSIAN_C表⽰每个区域块的阈值,由区域块内每个像素的灰度值经过⾼斯函数加权相乘后再相加,最后减去常量C得出adaptive_thresh1 = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,225,0)#⾃适应⾼斯加权
adaptive_thresh2 = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,225,0)#⾃适应平均缺点是可能会忽略掉区域内某些特殊的像素值=>例如照⽚中⾐服上的花纹
#不同类型的⾃适应⽅式对⽐
cv.namedWindow('img',cv.WINDOW_NORMAL)
cv.imshow('img',adaptive_thresh1)
cv.waitKey(0)
cv.imshow('img',adaptive_thresh2)
cv.waitKey(0)
cv.destroyAllWindows()
# Otsu阈值⾃动获取全局阈值,即⽆需⼿动决定阈值⼤⼩,阈值thresh⼤⼩默认0即可
ret,otsu_thresh1 = cv.threshold(gray,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
#ret ⾃动获取出来的值为99与原来的⼿动设置的127有⼀定的差距
ret,otsu_thresh2 = cv.threshold(gray,0,255,cv.THRESH_TOZERO+cv.THRESH_OTSU)
cv.namedWindow('img',cv.WINDOW_NORMAL)
cv.imshow('img',otsu_thresh1)
cv.waitKey(0)
cv.imshow('img',otsu_thresh2)
cv.waitKey(0)
cv.destroyAllWindows()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。