如何删除板周围的部分图像 - opencv

How to remove part of images around board - opencv

我正在与 ROI 合作,这个中心元素正是我要寻找的。但是上面这部分图片我需要删除。

smooth= cv2.GaussianBlur(gray, (3, 3), cv2.BORDER_DEFAULT)
T, thresh = cv2.threshold(smooth, 32, 255, cv2.THRESH_BINARY)

#roi = cv2.selectROI(thresh)
#print(roi)#=(2, 176, 36, 31)
roi_cropped = thresh[176:(176+31),2:(2+36)]

#kernel = np.ones((3, 3), np.uint8)
#erode = cv2.erode(roi_cropped, kernel) 
#show(erode)

contours, hierarchy = cv2.findContours(image=roi_cropped, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)

image_copy = img.copy()
cv2.drawContours(image=image_copy[176:(176+31),2:(2+36)], contours=contours, contourIdx=-1, color=(0, 255, 0), thickness=1, lineType=cv2.LINE_AA)
show(image_copy)

如果我没有误解你的问题,这是代码:

import cv2
import numpy as np


# load the image
image = cv2.imread("faces/stacl.png",0)

output = image.copy()

contours, hierarchy = cv2.findContours(image=output, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
    cv2.drawContours(output, contours, 1, 1, 44) #the key point of the code
#for the small image:
#cv2.drawContours(output, contours, 1, 1, 2)


ret,th=cv2.threshold(output,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
#for the small image:
#kernel=np.ones((2,2),np.uint8)
kernel=np.ones((12,5),np.uint8) 


open=cv2.morphologyEx(th,cv2.MORPH_OPEN,kernel) #bu

dist_transform = cv2.distanceTransform(open,cv2.DIST_L2,5)
cv2.imshow("Result", dist_transform)

cv2.waitKey(0)

很简单。检查轮廓的边界框是否触及图片的边缘。

# have `contours` from `roi_cropped`

(height, width) = roi_cropped.shape[:2]

for c in contours:
    (x, y, w, h) = bbox = cv.boundingRect(c)
    touches_edges = (x == 0) or (y == 0) or (x+w == width) or (y+h == height)
    print(touches_edges, ":", bbox)

你可以弄清楚如何擦除轮廓。有多个选项:

您可能甚至不需要擦除 那些斑点。只是忽略他们。