使用Python OpenCV查找图像中的极端外部点

发布于 2021-01-29 14:58:43

我有这个雕像的形象。

在此处输入图片说明

我正在尝试找到雕像上最顶部,最底部,最左侧和最右侧的点。有没有一种方法可以测量每边的边缘以确定雕像上最外面的点?我想得到双方的(x,y)坐标。我试图使用cv2.findContours()cv2.drawContours()获得雕像的轮廓。

import cv2

img = cv2.imread('statue.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

contours = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(img, contours, -1, (0, 200, 0), 3)

cv2.imshow('img', img)
cv2.waitKey()
关注者
0
被浏览
78
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是一种潜在的方法:


    转换为灰度并模糊图像后,我们阈值以获取二进制图像

    现在我们使用找到轮廓cv2.findContours()。由于OpenCV使用Numpy数组对图像进行编码,因此轮廓只是一个Numpy(x,y)坐标数组。我们可以对Numpy数组进行切片并使用argmin()argmax()确定像这样的外部左,右,上和下坐标

    left = tuple(c[c[:, :, 0].argmin()][0])
    right = tuple(c[c[:, :, 0].argmax()][0])
    top = tuple(c[c[:, :, 1].argmin()][0])
    bottom = tuple(c[c[:, :, 1].argmax()][0])
    

    这是结果

    左:(162,527)

    右:(463,467)

    最高:(250,8)

    底部:(381,580)

    import cv2
    import numpy as np
    
    # Load image, grayscale, Gaussian blur, threshold
    image = cv2.imread('1.png')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (3,3), 0)
    thresh = cv2.threshold(blur, 220, 255, cv2.THRESH_BINARY_INV)[1]
    
    # Find contours
    cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    c = max(cnts, key=cv2.contourArea)
    
    # Obtain outer coordinates
    left = tuple(c[c[:, :, 0].argmin()][0])
    right = tuple(c[c[:, :, 0].argmax()][0])
    top = tuple(c[c[:, :, 1].argmin()][0])
    bottom = tuple(c[c[:, :, 1].argmax()][0])
    
    # Draw dots onto image
    cv2.drawContours(image, [c], -1, (36, 255, 12), 2)
    cv2.circle(image, left, 8, (0, 50, 255), -1)
    cv2.circle(image, right, 8, (0, 255, 255), -1)
    cv2.circle(image, top, 8, (255, 50, 0), -1)
    cv2.circle(image, bottom, 8, (255, 255, 0), -1)
    
    print('left: {}'.format(left))
    print('right: {}'.format(right))
    print('top: {}'.format(top))
    print('bottom: {}'.format(bottom))
    cv2.imshow('thresh', thresh)
    cv2.imshow('image', image)
    cv2.waitKey()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看