Python 如何获取图像中的边界像素或已擦除区域

Python 如何获取图像中的边界像素或已擦除区域,python,image,image-processing,computer-vision,Python,Image,Image Processing,Computer Vision,假设我有一个被擦除的区域,现在我想知道这个区域的边界像素,我如何在Python中实现它? 嗯,我不运行就把代码写下来,你可以稍后自己试试 import numpy as np import cv2 as cv im = cv.imread('you_input_image.jpg') imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY) # assume the while area 255.255.255 are what you put manually a

假设我有一个被擦除的区域,现在我想知道这个区域的边界像素,我如何在Python中实现它?
嗯,我不运行就把代码写下来,你可以稍后自己试试

import numpy as np
import cv2 as cv
im = cv.imread('you_input_image.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
# assume the while area 255.255.255 are what you put manually and you want it removed. 
ret, thresh = cv.threshold(imgray, 254, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
# There might be multiple are with 255. then you need to find the index of the largest contour
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]
print cnt
# cnt contains all the point in this largest contour

您可以使用opencv来执行此操作。要使用的主要功能是
cv2.findContours

在下面用红色绘制边框

import cv2
import numpy as np
from skimage.color import rgb2gray
import matplotlib.pyplot as plt

im = plt.imread('uKTss.jpg')
gray = rgb2gray(im)

contours = cv2.findContours(gray.astype(np.uint8),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)[-2]

for contour in contours:  
    cv2.drawContours(im, contour, -1, (255, 0, 0), 1)

plt.imshow(im)
plt.show()