如何检测与背景颜色几乎相似的物体?

时间:2019-02-02 16:09:41

标签: python-3.5 opencv3.0

original image image after kmeans clustering

image I get as result

我正在使用厚血液显微镜图像进行疟原虫的检测。我试图对寄生虫对象进行分割,但是由于它们具有几乎相似的背景色,因此很难。我已经使用vv2.kmeans()对寄生虫和非寄生虫进行聚类。

import csv as csv
import matplotlib.pyplot as plt
def smooth(img):
dest=cv2.medianBlur(img,7)
#dest=cv2.GaussianBlur(img, (7,7),0)
return dest

def process(path,img):
   image=cv2.imread(path+img,1)
   image=smooth(image)
   return image

def kmeans(img,name):
   output=[]

image=img.reshape(img.shape[0]*img.shape[1],3)
image=np.float32(image)

nclusters=5
criteria=(cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER,10,1.0)
attempts=10
flags=cv2.KMEANS_RANDOM_CENTERS
compactness,labels,centers=cv2.kmeans(image,nclusters,None,criteria,attempts,flags)


centers = np.uint8(centers)
res = centers[labels.flatten()]
res2 = res.reshape((img.shape))

cv2.imwrite(dest+name[:-4]+'.png', res2)
im_color=cv2.imread(dest+name[:-4]+'.png',cv2.IMREAD_COLOR)
im_gray = cv2.cvtColor(im_color, cv2.COLOR_BGR2GRAY)


_, mask = cv2.threshold(im_gray, thresh=100, maxval=255, type=cv2.THRESH_BINARY_INV)

mask3 = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)  # 3 channel mask 


im_thresh_color = cv2.bitwise_and(img, mask3)


cv2.imwrite("C:\\Users\\user\\Desktop\\lbim2\\"+name[:-4] +".png",im_thresh_color)


def preprocess(path):
  images=[]
  j=0
  print ("Median Blur")
  for i in os.listdir(path):
    print(i)

    images.append(process(path,i))
    print(images[j].shape)
    #print(images[1].shape)
    images[j]=kmeans(images[j],i)
    j+=1
    print(i)


dest='../output1/'
print ("Preprocess")
preprocess('../input1/')

我得到的图像的所有像素值为0。黑色输出

0 个答案:

没有答案