图像的阈值与平滑

第1关:图像阈值分割

import cv2
import matplotlib.pyplot as plt
def thd():
    filepath='/data/workspace/myshixun/task1/'
    # 请根据左侧编程要求,完成图像阈值化操作:
    ########## Begin ##########
    img = cv2.imread(filepath+'cat.jpg')
    img = img[:,:,(2,1,0)]
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret1, thresh1 = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)
    ret2, thresh2 = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY_INV)
    ret3, thresh3 = cv2.threshold(img_gray, 150, 255, cv2.THRESH_TRUNC)
    ret4, thresh4 = cv2.threshold(img_gray, 150, 255, cv2.THRESH_TOZERO)
    ret5, thresh5 = cv2.threshold(img_gray, 150, 255, cv2.THRESH_TOZERO_INV)
    ########## End ##########

    # 作图并保存到指定路径
    titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
    images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
    for i in range(6):
        plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])
    plt.savefig(filepath+'out/threthold.png')

第2关:图像的平滑

import cv2
import matplotlib.pyplot as plt

# 使用图像平滑处理带噪声的图片
def flt():
    filepath = '/data/workspace/myshixun/task2/'
    # 请根据左侧编程要求,完成图像平滑操作:
    ########## Begin ##########
    img=cv2.imread(filepath+"pic.png")
    img = img[:,:,(2,1,0)]
    res1 = cv2.blur(img, (5,5))
    res2 = cv2.GaussianBlur(img,(5,5),0,0)
    res3 = cv2.boxFilter(img, -1, (5,5), False)
    res4 = cv2.medianBlur(img, 5)
   
   
    ########## End ##########

    # 作图并保存到指定路径
    titles = ['Blur', 'GaussianBlur', 'boxFilter', 'medianBlur']
    images = [res1, res2, res3, res4]
    # 分别画出四个子图,并保存为filter.png
    for i in range(4):
        plt.subplot(2, 2, i + 1), plt.imshow(images[i], 'gray')
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])
    plt.savefig(filepath+'out/filter.png')

???

猜你喜欢

转载自blog.csdn.net/weixin_44196785/article/details/115129260