python+opencv对图像进行二值化处理

一.采用Image类对图像进行明亮度,颜色,对比度等处理,去除图片上的干扰物。。。

# 图像增强
def image_enhance(image_path):
    img = cv2.imread(image_path, cv2.IMREAD_COLOR)
    img = Image.fromarray(img)
    # 明亮度增强
    img_bright = ImageEnhance.Brightness(img)
    brightness = 1.9
    img = img_bright.enhance(brightness)
    # 对比度增强
    img_contrast = ImageEnhance.Contrast(img)
    contrast = 2.0
    img = img_contrast.enhance(contrast)
    # 颜色增强
    img_color = ImageEnhance.Color(img)
    color = 3.5
    img = img_color.enhance(color)
    # 锐度增强
    img_sharp = ImageEnhance.Sharpness(img)
    sharpness = 3.2
    img = img_sharp.enhance(sharpness)

    img = np.array(img)
    return img

处理前:

处理后:

二.采用opencv对图片进行二值化处理

# 全局阈值
def threshold_demo(image):
    image = cv2.imread(image, cv2.IMREAD_COLOR)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
    print(ret)
    return binary


# 局部阈值
def local_threshold(image):
    image = cv2.imread(image, cv2.IMREAD_COLOR)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10)
    return binary


# 平均阈值
def custom_threshold(image):
    image = cv2.imread(image, cv2.IMREAD_COLOR)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    h, w = gray.shape[:2]
    m = np.reshape(gray, [1, w * h])
    mean = m.sum() / (h * w)
    print(mean)
    ret, binary = cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY)
    return binary

处理前:

处理后:

 

你可能感兴趣的:(python,图像,opencv)