python实现图像阴影去除

导入依赖

import cv2
import numpy as np

最大滤波

def max_filter(image,filter_size):
    # padding操作,在最大滤波中需要在原图像周围填充(filter_size//2)个小的数字,一般取-1
    # 先生成一个全为-1的矩阵,大小和padding后的图像相同
    empty_image = np.full((image.shape[0] + (filter_size // 2) * 2, image.shape[1] + (filter_size // 2) * 2), -1)
    # 将原图像填充进矩阵
    empty_image[(filter_size // 2):empty_image.shape[0] - (filter_size // 2),
    (filter_size // 2):empty_image.shape[1] - (filter_size // 2)] = image.copy()
    # 创建结果矩阵,和原图像大小相同
    result = np.full((image.shape[0], image.shape[1]), -1)

    # 遍历原图像中的每个像素点,对于点,选取其周围(filter_size*filter_size)个像素中的最大值,作为结果矩阵中的对应位置值
    for h in range(filter_size // 2, empty_image.shape[0]-filter_size // 2):
        for w in range(filter_size // 2, empty_image.shape[1]-filter_size // 2):
            filter = empty_image[h - (filter_size // 2):h + (filter_size // 2) + 1,
                     w - (filter_size // 2):w + (filter_size // 2) + 1]
            result[h-filter_size // 2, w-filter_size // 2] = np.amax(filter)
    return result

最小滤波

def min_filter(image,filter_size):
    # padding操作,在最大滤波中需要在原图像周围填充(filter_size//2)个大的数字,一般取大于255的
    # 先生成一个全为-1的矩阵,大小和padding后的图像相同
    empty_image = np.full((image.shape[0] + (filter_size // 2) * 2, image.shape[1] + (filter_size // 2) * 2), 400)
    # 将原图像填充进矩阵
    empty_image[(filter_size // 2):empty_image.shape[0] - (filter_size // 2),
    (filter_size // 2):empty_image.shape[1] - (filter_size // 2)] = image.copy()
    # 创建结果矩阵,和原图像大小相同
    result = np.full((image.shape[0], image.shape[1]), 400)

    # 遍历原图像中的每个像素点,对于点,选取其周围(filter_size*filter_size)个像素中的最小值,作为结果矩阵中的对应位置值
    for h in range(filter_size // 2, empty_image.shape[0]-filter_size // 2):
        for w in range(filter_size // 2, empty_image.shape[1]-filter_size // 2):
            filter = empty_image[h - (filter_size // 2):h + (filter_size // 2) + 1,
                     w - (filter_size // 2):w + (filter_size // 2) + 1]
            result[h-filter_size // 2, w-filter_size // 2] = np.amin(filter)
    return result

合并结果

def remove_shadow(image_path):
    image = cv2.imread(image_path, 0)

    max_result=max_filter(image,30)
    min_result=min_filter(max_result,30)
    result=image-min_result
    result=cv2.normalize(result, None, 0, 255, norm_type=cv2.NORM_MINMAX)
    return result

测试:

if __name__=="__main__":
    result=remove_shadow('Test.jpg')
    cv2.imwrite("./out1.jpg", result)
  • 6
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值