利用python对图片进行二值化处理
# 图片二值化
from PIL import Image
img = Image.open('test.jpg')
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
Img = img.convert('L')
Img.save("test1.jpg")
# 自定义灰度界限,大于这个值为黑色,小于这个值为白色
threshold = 200
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
# 图片二值化
photo = Img.point(table, '1')
photo.save("test2.jpg")
利用python+opencv对图片进行二值化处理
import cv2
#读取图片
src = cv2.imread('test.jpg')
#灰度图像处理
GrayImage = cv2.cvtColor(src,cv2.COLOR_BGR2GRAY)
#二进制阈值化处理
r, b = cv2.threshold(GrayImage, 180, 255, cv2.THRESH_BINARY)
print(r)
print(b)
# 保存图片:就是把数组保存成图片
import PIL
from PIL import Image
im = Image.fromarray(b)
im.save("test_result.png")
#显示图像
cv2.imshow("src", src)
cv2.imshow("result", b)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
#src:是图片源
#thresh:是阈值
#type:表示的是这里划分的时候,用的什么算法,下面代码中使用的THRESH_BINARY的意思是:
#大于180的全部变成255;小于180的全部变成0。
#返回的retval是阈值,dst是图像的数组