如何将图像中的深黑框变成白色?

问题描述 投票:0回答:1

我有第一张图像,图像周围有一个巨大的白色背景,然后是一个较暗的框架。我想去掉图像周围多余的白色部分以及暗框。基本上我想要像下面第二张图片一样的图像。我该如何做到这一点,最好使用 PIL 库(如果不是 OpenCv 也可以)?抱歉进行编辑,但这些是我正在使用的原始图像。谢谢!

opencv image-processing python-imaging-library
1个回答
0
投票

按照stateMachine的建议,这是一个使用opencv的python实现:

import cv2

filename = 'input_image.jpg'
input_image = cv2.imread(filename)
grayscale_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
# use Otsu's method to determine the threshold
threshold, binary_image = cv2.threshold(grayscale_image,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
contours, hierarchy  = cv2.findContours(binary_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# contours are sorted from large to small, use the second because the first
# describes the entire image. find left, top, right and bottom coordinates of # the second contour by finding the smallest x and y values for points on the # contour, than the largest

left = contours[1][:, 0, 0].min()
top = contours[1][:, 0, 1].min()

right = contours[1][:, 0, 0].max()
bottom = contours[1][:, 0, 1].max()

# crop the target image from the input image

cropped_image = input_image[top:bottom+1, left:right+1, :]

© www.soinside.com 2019 - 2024. All rights reserved.