簡體   English   中英

使用 opencv 獲取由橢圓包圍的圖像區域中的像素坐標和像素值 python

[英]Getting pixel coordinates and pixel values in image region bounded by an ellipse using opencv python

我想在 python 中的 opencv 圖像上繪制任意橢圓,然后返回兩個 arrays:(1) 由橢圓包圍的所有像素的像素坐標,包括橢圓線上和橢圓內,(2) 像素值來自數組 (1) 的每個像素。

我看了這個答案,但它只考慮橢圓輪廓上的點而不是內部區域。

使用此代碼,您可以獲得橢圓內的每個像素:

from math import sin, cos

def get_y_ellipse(ellipse_size, x, alpha):
    a, b = ellipse_size[0] / 2, ellipse_size[1] / 2
    delta_sqrt = ((b**4-2*a**2*b**2+a**4)*sin(2*alpha)**2*x**2-4*a**4*x**2*cos(alpha)**2*sin(alpha)**2-4*a**2*b**2*x**2*cos(alpha)**2+4*a**4*b**2*cos(alpha)**2-4*a**2*b**2*x**2*sin(alpha)**4-4*b**4*x**2*sin(alpha)**2*cos(alpha)**2+4*a**2*b**4*sin(alpha)**2)**(1/2)
    y1 = ((-b**2 + a**2)*sin(2*alpha)*x + delta_sqrt) / (2*a**2*cos(alpha)**2+2*b**2*sin(alpha)**2)
    y2 = ((-b**2 + a**2)*sin(2*alpha)*x - delta_sqrt) / (2*a**2*cos(alpha)**2+2*b**2*sin(alpha)**2)
    return y1, y2

ellipse_size = (100, 50)
ellipse_rotation = 45 # deg
ellipse_center_position = (0,0)

pixels = []

for x in range(ellipse_center_position[0] - ellipse_size[0], ellipse_center_position[0] + ellipse_size[0]):
    y1, y2  = get_y_ellipse(ellipse_size, x, ellipse_rotation)
    if complex not in map(type, (y1, y2)):
        for y in range(int(y1), int(y2), -1):
            pixels.append([x, y])

# 'pixels' is a 1d array that contain every pixel [x,y] format

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM