完成目标区域提取
import cv2
import numpy as np
img_path=r'E:\Desktop\DDSM\Benign\11_C_0217_1.RIGHT_CC.LJPEG.1_highpass.png'
img=cv2.imread(img_path)
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
cv2.imshow('gra',gray)
gray = np.array(gray)
gray[:25,:]=0
gray[int(gray.shape[0])-25:int(gray.shape[0])]=0
print('image shape: ', gray.shape)
blurred =cv2.GaussianBlur(gray,(9,9),0)
cv2.imshow('blur',blurred)
gradX = cv2.Sobel(gray,cv2.CV_32F,dx=1,dy=0)
gradY = cv2.Sobel(gray,cv2.CV_32F,dx=0,dy=1)
gradient = cv2.subtract(gradX,gradY)
gradient = cv2.convertScaleAbs(gradient)
cv2.imshow('gradient',gradient)
_,thresh = cv2.threshold(blurred,30,255,cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(25,25))
cv2.imshow('thr',thresh)
cnts,_= cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts,key=cv2.contourArea,reverse=True)
print(len(cnts))
draw_img = cv2.drawContours(img,[cnts[0]],-1,(0,0,255),3)
cv2.imshow('draw_img',draw_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|