opencv python 3 数值操作
像素相加
cv2.add()实现了两张图像的像素相加,且当和大于255时取255。
import cv2
import numpy as np
x = np.uint8([250])
y = np.uint8([10])
print(cv2.add(x, y))
print(x + y)
输出结果为:
[[255]]
[4]
x+y输出4是因为超过了uint8的范围0-255。
带权相加
addWeighted()实现了带权相加,如:
x = np.uint8([250])
y = np.uint8([10])
print(cv2.addWeighted(x, 0.1, y, 0.9, 5))
输出结果为:
[[39]]
其中0.1和0.9为两个输入的权值,5为偏移。
阈值变换
cv2.threshold()提供了将灰度图像根据某一阈值改变所有像素值的功能。
retval, dst = cv.threshold(src, thresh, maxval, type[, dst])
- retval:若使用了THRESH_OTSU或THRESH_TRIANGLE产生的阈值
- dst:输出图像
- src:输入图像
- thresh:阈值
- maxval:对超出阈值的像素点设定的像素值
type:阈值变换类型,包括:
其中前5个为变换方式,后2个为自动生成阈值的方法,分别根据otsu算法和triangle算法。
img = cv2.imread('a.jpg', 0)
ret, img_after = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('img', img_after)
cv2.waitKey()
img = cv2.imread('a.jpg', 0)
ret, img_after = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(ret)
cv2.imshow('img', img_after)
cv2.waitKey()
并输出根据算法计算得到的阈值146。