我如何识别图像?

How can i identify image?

我有一个没有几何形状的物体,无法轻松找到长度和宽度,但我想编写代码通过找到最长和最小值并除以二来测量平均长度和宽度。我有这个代码:

And it outputs this [image]



像这样的示例可以从 img.shape 访问高度、宽度和通道数:高度在索引 0 处,宽度在索引 1 处;和索引 2 处的通道数。

import cv2
# read image
img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)
 
# get dimensions of image
dimensions = img.shape
 
# height, width, number of channels in image
height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]
 
print('Image Dimension    : ',dimensions)
print('Image Height       : ',height)
print('Image Width        : ',width)
print('Number of Channels : ',channels)

输出:

Image Dimension    :  (149, 200, 4)
Image Height       :  149
Image Width        :  200
Number of Channels :  4

您还可以在 https://www.tutorialkart.com/opencv/python/

找到更完整的库

在这个页面 https://docs.opencv.org/3.4/d1/d32/tutorial_py_contour_properties.html 他们展示了如何计算轮廓的所有属性,如果你想看的话,无论如何 cv2.boundingRect(cnt) 已经计算了一个近似矩形的宽度测量和高度(w,h)我做了一个小程序来绘制这个矩形及其尺寸,结果如下:

您可以使用

1 - 轮廓内的区域:

area = cv.contourArea(cnt)

2 - 等效直径 - 面积与等高线面积相同的圆的直径

equi_diameter = np.sqrt(4*area/np.pi)

3 - 轮廓周长 - 也称为弧长。

perimeter = cv.arcLength(cnt,True)

我有一个两步解决方案


    1. 应用 Canny
    1. 使用line-detector
    2. 求长度

应用Canny将得到结果:

现在找我们找长度更方便了:

代码:


import cv2

img = cv2.imread("JxHmm.png")
gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cny = cv2.Canny(gry, 50, 200)
lns = cv2.ximgproc.createFastLineDetector().detect(cny)
cpy = img.copy()

(h, w) = cpy.shape[:2]

min_x = w
min_y = h
max_x = 0
max_y = 0

for ln in lns:
    x1 = int(ln[0][0])
    y1 = int(ln[0][1])
    x2 = int(ln[0][2])
    y2 = int(ln[0][3])

    min_x = min(x1, x2, min_x)
    min_y = min(y1, y2, min_y)
    max_x = max(x1, x2, max_x)
    max_y = max(y1, y2, max_y)

    # print("Coords: ({}, {})->({}, {})".format(x1, y1, x2, y2))


cv2.line(cpy, pt1=(min_x, min_y), pt2=(max_x, min_y), color=(0, 255, 0), thickness=10)
cv2.putText(cpy, '({}, {})'.format(min_x, min_y), (min_x - 10, (min_y - 30)), cv2.FONT_HERSHEY_SIMPLEX, 2,
            (0, 255, 0), 3, cv2.LINE_AA)
cv2.putText(cpy, '({}, {})'.format(max_x, min_y), (max_x - 340, (min_y - 30)), cv2.FONT_HERSHEY_SIMPLEX, 2,
            (0, 255, 0), 3, cv2.LINE_AA)
cv2.putText(cpy, '{} pixel'.format((max_x - min_x)), (int((max_x + min_x)/2), (min_y - 30)), cv2.FONT_HERSHEY_SIMPLEX,
            2, (0, 255, 0), 3, cv2.LINE_AA)
cv2.line(cpy, pt1=(min_x, min_y), pt2=(min_x, max_y), color=(0, 0, 255), thickness=10)
cv2.putText(cpy, '({}, {})'.format(min_x, min_y), (min_x - 10, (min_y + 50)), cv2.FONT_HERSHEY_SIMPLEX, 2,
            (0, 0, 255), 3, cv2.LINE_AA)
cv2.putText(cpy, '({}, {})'.format(min_x, max_y), (min_x - 10, (max_y - 10)), cv2.FONT_HERSHEY_SIMPLEX, 2,
            (0, 0, 255), 3, cv2.LINE_AA)
cv2.putText(cpy, '{} pixel'.format(max_y - min_y), (min_x - 150, int((max_y + min_y)/2) + 20), cv2.FONT_HERSHEY_SIMPLEX, 2,
            (0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow("cpy", cpy)
cv2.waitKey(0)