简体   繁体   English

如何获取图像中的边框像素或擦除区域

[英]How to get the border pixels or erased area in an image

Imagine I have the following image with an erased area, now I want to know the border pixels of this area, how can I achieve it in Python?想象我有下面的图像,有一个擦除区域,现在我想知道这个区域的边界像素,我如何在Python中实现它? The image with one area being erased一个区域被擦除的图像

Emm i`ll just put down the code without running, you can try it later on yourself. emmm 不运行就放下代码,以后自己试试。

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

You can use opencv to do this.您可以使用 opencv 来执行此操作。 The main function to use is cv2.findContours要使用的主要功能是cv2.findContours

Drawing the border in red below.在下面用红色绘制边框。

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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM