【问题标题】:Unable to get a Proper contour无法获得适当的轮廓
【发布时间】:2017-03-12 18:38:38
【问题描述】:

我试图区分矩形、梯形和半圆形。所以我所做的是在形状周围画一个轮廓,然后是一个旋转的矩形。之后,我找到轮廓和旋转矩形的面积并取它们的比例。使用这个比率,我将确定形状,因为前面提到的三种形状会有所不同。

(如果有人有更可靠的方法来区分这三者,我们将不胜感激。)

解决问题。我无法在图像周围绘制适当的轮廓。 这是输入和输出图像:

这是我的代码

import cv2
import numpy as np

img = cv2.imread('h4.JPG')
cv2.imshow('Input',img)
#img = cv2.resize(img, None, fx=0.2,fy=0.2)
img = cv2.GaussianBlur(img, (11,11), 0)
img = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)
im = img.copy()

imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,0,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

max = 0

for c in contours:
    area = cv2.contourArea(c)
    print area
    if(np.any(max <= area)):
        max = c


A, B, C = cv2.minAreaRect(c)
rotrect = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(rotrect)
box = np.int0(box)
cv2.drawContours(im, contours, 0, (0,255,0), 2)
cv2.drawContours(im, [box], 0, (0,0,255), 2)

areaS = cv2.contourArea(contours[0])
areaR = B[0]*B[1]

Ratio = areaS/areaR

print "Shape Area: ",areaS
print "Shape Rect: ",areaR
print "Ratio: ",Ratio

cv2.imshow('Output',im)

if cv2.waitKey() and 0xff == 27:
    cv2.destroyAllWindows()

提前致谢。

【问题讨论】:

  • 使用更高的阈值:ret,thresh = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY)。您 去噪 创建非零像素,findContours 将其视为 前景
  • 谢谢@Miki。它有帮助。但是请告诉我您为什么特别选择 127 作为阈值
  • 高到足以删除低值(几乎是黑色)但又不会太高而无法删除高值(几乎是白色)的东西。 127在中间;)。从 30 到 220 的任何值都可能也有效
  • 再次感谢:-D
  • 很高兴它有帮助。请发布正确的代码、结果和解释作为答案并接受它...或删除问题...您的选择;)

标签: python python-2.7 opencv image-processing


【解决方案1】:

我已经在 cmets 部分发布了带有 Miki 提供的解决方案的代码。

代码:

im = cv2.imread('Figure.jpg', 1)
gray_img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
im1 = im.copy()                       #---copy of the original image----

ret, thresh = cv2.threshold(gray_img, 127, 255, 0)   
blur_img = cv2.GaussianBlur(thresh, (11,11), 0)

#---Finding and drawing contours---
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im1, contours, -1, (0, 255, 0), 3)

#----Drawing a rotated rectangle----
cnt = contours
rect = cv2.minAreaRect(cnt[0])  #---I used cnt[0] since there is only one contour, if there are more you can assign this within a for loop----
box = cv2.boxPoints(rect)
box = np.int0(box)
im = cv2.drawContours(im1, [box], 0, (0,0,255), 2)

cv2.imshow("Final_Image.jpg", im1)

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2022-01-10
    • 2017-07-08
    • 2020-09-03
    • 2013-08-23
    • 1970-01-01
    相关资源
    最近更新 更多