首页 文章

opencv轮廓区域

提问于
浏览
2

我试图从图片中找到动物的轮廓 . 我们假设它是一只鸡 . 从图片中我可以找到它的轮廓但它们没有关闭 . 此外,我从背景中得到很多噪音(白色和鸡肉一样) . 我正在使用stackoverflow上找到的简单代码 .

import numpy as np
import cv2

img = cv2.imread('lateral.jpg')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# blurred = cv2.GaussianBlur(imgray, (5, 5), 0)
# edged = cv2.Canny(blurred, 10, 11) # 10 and 40 to be more perceptive
# contours_canny= cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
edges = cv2.Canny(imgray, 10,30)    

cv2.imshow('edges', edges)
k = cv2.waitKey()

The result is this one.

This is the original Image

有没有办法找到这只鸡的轮廓?提前致谢 .

1 回答

  • 0

    寻找轮廓非常容易 . 问题是你的图像在鸡肉和背景之间的对比度很低 . 所以,你使用精简边缘的想法并不坏,它只需要一些后期处理 .

    我想这就是你要找的东西:

    import cv2
    import numpy as np
    
    
    image = cv2.imread("./chicken.jpg", cv2.IMREAD_COLOR)
    image = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 
    
    
    imgray = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)[...,0]
    edges = cv2.Canny(imgray, 10,30)    
    blurred = cv2.GaussianBlur(edges, (9, 9), 0)
    clahe = cv2.createCLAHE(clipLimit=5.0, tileGridSize=(32,32))
    contrast = clahe.apply(blurred)
    ret, thresh = cv2.threshold(contrast, 20, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
    _, contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    
    maxArea = 0
    best = None
    for contour in contours:
      area = cv2.contourArea(contour)
      print (area)
      if area > maxArea :
    
        maxArea = area
        best = contour
    
    
    cv2.drawContours(image, [best], 0, (0, 0, 255), -1)
    
    while True:
      cv2.imshow("result", image)
      k = cv2.waitKey(30) & 0xff
      if k == 27:
          break
    

    enter image description here

相关问题