简体   繁体   中英

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? The image with one area being erased

Emm i`ll just put down the code without running, you can try it later on yourself.

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. The main function to use is 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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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