久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何獲取圖像中形狀每一邊的長度?

How to get length of each side of a shape in an image?(如何獲取圖像中形狀每一邊的長度?)
本文介紹了如何獲取圖像中形狀每一邊的長度?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

假設我們有如下圖片:

[![輸入][1]][1]

我想確定邊的數量,以及每邊的長度.

在圖像中,我們將三個邊緣作為直線,而上一個是彎曲的邊緣.我能夠使用 Canny 邊緣檢測找到三個直邊的長度.我們可以有四個頂點坐標,我們可以計算出三個直邊/線的長度,但無法找到彎曲邊的長度.

因此,預處理必須適應輸入圖像,并且超出了我的回答范圍!在下面的代碼中,預處理是針對給定的輸入圖像,而不是針對其他兩個示例.

import cv2將 matplotlib.pyplot 導入為 plt將 numpy 導入為 npdef extract_and_measure_edges(img_bin):# 檢測可能的角點,并提取候選者dst = cv2.cornerHarris(img_bin, 2, 3, 0.04)糖果= []對于 i, c in enumerate(np.argwhere(dst > 0.1 * np.max(dst)).tolist()):c = np.flip(np.array(c))如果 len(cand) == 0:cand.append(c)別的:添加=真對于 enumerate(cand) 中的 j,d:d = np.array(d)如果 np.linalg.norm(c - d) <5:添加 = 假休息如果添加:cand.append(c)# 獲取實際的、最近的匹配輪廓點的索引角=排序([np.argmin(np.linalg.norm(c-cnt.squeeze(),軸=1))對于 c 中的 cand])# 從輪廓中提取邊緣,并測量它們的長度輸出 = cv2.cvtColor(np.zeros_like(img_bin), cv2.COLOR_GRAY2BGR)對于 i_c, c in enumerate(corners):如果 i_c == len(corners) - 1:edge = np.vstack([cnt[c:, ...], cnt[0:corners[0], ...]])別的:邊緣 = cnt[c:corners[i_c + 1], ...]loc = tuple(np.mean(edge.squeeze(), axis=0, dtype=int).tolist())顏色 = 元組(np.random.randint(0, 255, 3).tolist())長度 = cv2.arcLength(邊,假)cv2.polylines(輸出,[邊緣],假,顏色,2)cv2.putText(輸出,'{:.2f}'.format(長度),loc,cv2.FONT_HERSHEY_COMPLEX,0.5,顏色,1)返回輸出# 讀取并預處理圖像,提取形狀輪廓# TODO:修改以適合您的輸入圖像img = cv2.imread('2B2m4.png')灰色 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)thr = cv2.threshold(灰色, 16, 255, cv2.THRESH_BINARY_INV)[1]cnts = cv2.findContours(thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)cnts = cnts[0] 如果 len(cnts) == 2 否則 cnts[1]cnt = max(cnts, key=cv2.contourArea)thr = cv2.drawContours(np.zeros_like(thr), [cnt], -1, 255, 1)# 提取和測量邊緣,并可視化輸出out = extract_and_measure_edges(thr)plt.figure(figsize=(18, 6))plt.subplot(1, 3, 1), plt.imshow(img), plt.title('原始輸入圖像')plt.subplot(1, 3, 2), plt.imshow(thr, cmap='gray'), plt.title('需要輪廓')plt.subplot(1, 3, 3), plt.imshow(out), plt.title('結果')plt.tight_layout(), plt.show()

這是輸出:

示例 #2:

輸出:

示例 #3:

輸出:

(我沒有注意正確的顏色順序...)

----------------------------------------系統信息--------------------------------------平臺:Windows-10-10.0.19041-SP0蟒蛇:3.9.1PyCharm:2021.1.1Matplotlib:3.4.2NumPy:1.19.5開放CV:4.5.2--------------------------------------

Suppose we have an image as below:

[![Input][1]][1]

I want to determine the number of sides, and the length of each side.

Here in the image, we have three edges as straight lines, and the upper one is a curved edge. I am able to find the length of the three straight edges using Canny edge detection. We can have four vertices coordinates, and we can calculate the length of the three straight edges/lines, but unable to find the length of the curved edge.

find number of sides and length of each side and number of vertices in image python This is a good answer for getting the number of edges in an image, and we get the coordinates of vertices through the code in the above link. Further to get the length of the sides using the coordinates, we can use below code to get the length, if the edges are straight lines:

for pt in zip(points,np.roll(points,-1,0)):
#     print( pt )
    x = pt[0][0]
    y = pt[1][0]
    d = math.sqrt((x[1]-y[1])*(x[1]-y[1]) + (x[0]-y[0])*(x[0]-y[0]))
    print('length between point:',x,'and', y,'is', d)

To simplify my question: I want to find, how many edges/sides are there for a shape in an image, and their respective lengths, if the image shape has any curved sides.

解決方案

My idea would be to get the contour of the shape, try to detect "corners", e.g. using Harris corner detection, find matching points from the contour, and piecewise calculate the length of the edges using cv2.arcLength.

The input for the below extract_and_measure_edges method needs some binarized contour image like that one derived from your actual input image:

So, the pre-processing must be adapted to the input images, and is out of scope of my answer! In the below code, the pre-processing is for the given input image, not for the two other examples.

import cv2
import matplotlib.pyplot as plt
import numpy as np


def extract_and_measure_edges(img_bin):

    # Detect possible corners, and extract candidates
    dst = cv2.cornerHarris(img_bin, 2, 3, 0.04)
    cand = []
    for i, c in enumerate(np.argwhere(dst > 0.1 * np.max(dst)).tolist()):
        c = np.flip(np.array(c))
        if len(cand) == 0:
            cand.append(c)
        else:
            add = True
            for j, d in enumerate(cand):
                d = np.array(d)
                if np.linalg.norm(c - d) < 5:
                    add = False
                    break
            if add:
                cand.append(c)

    # Get indices of actual, nearest matching contour points
    corners = sorted([np.argmin(np.linalg.norm(c - cnt.squeeze(), axis=1))
                      for c in cand])

    # Extract edges from contour, and measure their lengths
    output = cv2.cvtColor(np.zeros_like(img_bin), cv2.COLOR_GRAY2BGR)
    for i_c, c in enumerate(corners):
        if i_c == len(corners) - 1:
            edge = np.vstack([cnt[c:, ...], cnt[0:corners[0], ...]])
        else:
            edge = cnt[c:corners[i_c + 1], ...]

        loc = tuple(np.mean(edge.squeeze(), axis=0, dtype=int).tolist())
        color = tuple(np.random.randint(0, 255, 3).tolist())
        length = cv2.arcLength(edge, False)
        cv2.polylines(output, [edge], False, color, 2)
        cv2.putText(output, '{:.2f}'.format(length), loc, cv2.FONT_HERSHEY_COMPLEX, 0.5, color, 1)
    return output


# Read and pre-process image, extract contour of shape
# TODO: MODIFY TO FIT YOUR INPUT IMAGES
img = cv2.imread('2B2m4.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thr = cv2.threshold(gray, 16, 255, cv2.THRESH_BINARY_INV)[1]
cnts = cv2.findContours(thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnt = max(cnts, key=cv2.contourArea)
thr = cv2.drawContours(np.zeros_like(thr), [cnt], -1, 255, 1)

# Extract and measure edges, and visualize output
out = extract_and_measure_edges(thr)
plt.figure(figsize=(18, 6))
plt.subplot(1, 3, 1), plt.imshow(img), plt.title('Original input image')
plt.subplot(1, 3, 2), plt.imshow(thr, cmap='gray'), plt.title('Contour needed')
plt.subplot(1, 3, 3), plt.imshow(out), plt.title('Results')
plt.tight_layout(), plt.show()

That's the output:

Example #2:

Output:

Example #3:

Output:

(I haven't paid attention to the correct color ordering...)

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.1
Matplotlib:    3.4.2
NumPy:         1.19.5
OpenCV:        4.5.2
----------------------------------------

這篇關于如何獲取圖像中形狀每一邊的長度?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 日本免费黄色 | 欧美视频 亚洲视频 | 婷婷福利 | 亚洲精品小视频在线观看 | 亚洲不卡在线观看 | av天天干 | 日日操夜夜操天天操 | 一区二区三区四区在线 | 在线啊v| 精品一区二区三区av | 亚洲精品欧美一区二区三区 | 成人毛片在线视频 | 日韩高清一区二区 | 亚洲精品v| 国产亚洲一区二区精品 | 黄色电影在线免费观看 | 免费黄色特级片 | www.国产视频 | 中文字幕第二区 | 中文成人在线 | 精品久久久久久久人人人人传媒 | 日本韩国欧美在线观看 | 一区二区精品在线 | 欧美精品日韩精品国产精品 | 亚洲精品日韩综合观看成人91 | 日韩一级免费大片 | 日韩电影一区二区三区 | 亚洲欧美精品在线 | 精品国产欧美一区二区 | 成年人在线观看视频 | 国产精品s色 | 91天堂网 | 中文字幕第一页在线 | 成人教育av | 成人在线免费观看视频 | 天天操天天干天天曰 | 97伦理电影 | 欧美三级电影在线播放 | 一本岛道一二三不卡区 | 91丨九色丨国产在线 | 精品亚洲永久免费精品 |