1

我有一张图片

http://imgur.com/a/VXG6h (egg1.png)

我想只识别(提取)鸡蛋。

我的代码主要基于http://docs.opencv.org/3.2.0/d3/db4/tutorial_py_watershed.html import numpy as np import cv2

log_on = True
img = cv2.imread('egg1.png')

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)

# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)

ret, sure_fg = cv2.threshold(dist_transform,0.5*dist_transform.max(),255,0)

# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)

# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)

# Add one to all labels so that sure background is not 0, but 1
markers = markers+1

# Now, mark the region of unknown with zero
markers[unknown==255] = 0

markers = cv2.watershed(img,markers)
for marker in np.unique(markers):
    if marker == 0:
        continue
    mask = np.zeros(gray.shape, dtype="uint8")
    mask[markers == marker] = 255

    # detect contours in the mask and grab the largest one
    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
            cv2.CHAIN_APPROX_SIMPLE)[-2]

    c = max(cnts, key=cv2.contourArea)
    # draw a circle enclosing the object
    ((x, y), r) = cv2.minEnclosingCircle(c)
    cv2.circle(img, (int(x), int(y)), int(r), (0, 255, 0), 2)
    cv2.putText(img, "#{}".format(marker), (int(x) - 10, int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

img[markers == -1] = [255,0,0]

cv2.imshow('img_out', img)

if log_on:
    cv2.imshow('gray', gray)
    cv2.imshow('thresh', thresh)
    cv2.imshow('opening', opening)
    cv2.imshow('sure_bg', sure_bg)
    cv2.imshow('dist_transform', dist_transform)
    cv2.imshow('sure_fg', sure_fg)
    cv2.imshow('unknown', unknown)

    #cv2.imwrite('gray.png', gray)
    #cv2.imwrite('thresh.png', thresh)
    #cv2.imwrite('opening.png', opening)
    #cv2.imwrite('sure_bg.png', sure_bg)
    #cv2.imwrite('dist_transform.png', dist_transform)
    #cv2.imwrite('sure_fg.png', sure_fg)
    #cv2.imwrite('unknown.png', unknown)
    #cv2.imwrite('img_out.png', img)

key = cv2.waitKey(0)
if key == 27: # wait for ESC key to exit
    cv2.destroyAllWindows()
cv2.destroyAllWindows()

但是,我在使用白色背景以及“脱粒”图像中显示的鸡蛋的闪亮部分时遇到了很大的麻烦。

我如何“均匀”出鸡蛋的不均匀颜色(去除渐变?)?

这是我的代码的结果http://imgur.com/a/cdoWl

任何帮助将不胜感激,并提前致谢

4

0 回答 0