PIL的point()函数进行二值化处理

import pylab
from PIL import Image, ImageEnhance
from skimage import img_as_ubyte, img_as_float
import numpy as np
def plot_image(image, title=""):
    # pylab.gray()
    pylab.title(title, size=20)
    pylab.imshow(image, cmap='gray')
    # image.show()
    pylab.axis('off')

def plot_hist(r, g, b, title=''):
    r, g, b = img_as_ubyte(r), img_as_ubyte(g), img_as_ubyte(b)
    pylab.hist(np.array(r).ravel(), bins=256,
               range=(0, 256), color='r', alpha=0.5)
    pylab.hist(np.array(g).ravel(), bins=256,
               range=(0, 256), color='g', alpha=0.5)
    pylab.hist(np.array(b).ravel(), bins=256,
               range=(0, 256), color='b', alpha=0.5)
    pylab.xlabel('pixel value', size=20)
    pylab.ylabel('frequency', size=20)
    pylab.title(title, size=20)
    # pylab.axis('off')

im = Image.open('./9781789343731_Code/images/swans.jpg').convert('L')
pylab.imshow(im)
pylab.show()
pylab.hist(np.array(im).ravel(), bins=256, range=(0, 256), color='g')
pylab.xlabel('pixel values')
pylab.ylabel('Frequency')

pylab.title('Histogram')
pylab.show()

pylab.figure(figsize=(12, 18))
# pylab.gray()
pylab.subplot(2, 2, 1)
plot_image(im, 'original image')
pylab.axis('off')

th = [0, 50, 100, 150, 200]
for i in range(2, 5):
    im1 = im.point(lambda x: x>th[i] ,'1')
    pylab.subplot(2,2,i)
    plot_image(im1, 'binary image threshold= ' + str(th[i]))

pylab.show()

im = Image.open('./9781789343731_Code/images/swans.jpg').convert('L')
im = Image.fromarray(np.clip(im + np.random.randint(-128, 128,
                                                    (im.height,im.width)),
                             0, 255).astype(np.uint8))

pylab.figure(figsize=(12, 18))

pylab.subplot(2, 2, 1)
plot_image(im, 'original image with noise')

th = [0, 50, 100, 150, 200]
for i in range(2, 5):
    im1 = im.point(lambda x: x>th[i], '1')
    pylab.subplot(2,2, i)
    plot_image(im1, 'binary image with threshod ' + str(th[i]))

pylab.show()

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值