How to get value of pixels which are at a certain angle from another pixel?

坚强是说给别人听的谎言 提交于 2021-01-27 18:41:12

问题


I'm trying to implement a method where I have to obtain the values of all those pixels which forms a line at a certain angle through a pixel (i, j)

Consider the following code snippet

sum = image.getpixel(((i - 7), (j + 2))) + image.getpixel(((i - 6), (j + 2))) + image.getpixel(
    ((i - 5), (j + 1))) + image.getpixel(
    ((i - 4), (j + 1))) + image.getpixel(((i - 3), (j + 1))) + image.getpixel(((i - 2), (j + 1))) + image.getpixel(
    ((i - 1), j)) + image.getpixel((i, j)) + image.getpixel(((i + 1), j)) + image.getpixel(
    ((i + 2), (j - 1))) + image.getpixel(((i + 3), (j - 1))) + image.getpixel(((i + 4), (j - 1))) + image.getpixel(
    ((i + 5), (j - 1))) + image.getpixel(((i + 6), (j - 2))) + image.getpixel(((i + 7), (j - 2)))
avg_sum = sum / 15

Now in the above code I know which pixels relative to i, j forms the line at angle 15 degrees. Hence I am able to get the values of all those pixels.

Now is there an easy way to do this because currently this code find the sum of the grey level of 15 pixels that forms this line at 15 degree through i, j. I want this code to be flexible so that I can easily find the sum of line of length 15 pixels or 13 pixels or 11 pixels and so on.


回答1:


You can use some trigonometry. Recall that sin(angle) = y/x, so y = x*sin(angle). Just create an array of x values however long you want, and then plug it into the formula for the y values. You'll of course need to round the y values afterwards. And then you can translate all of them to the starting location for the line.

>>> import numpy as np
>>> angle = 15*np.pi/180
>>> x = np.arange(0,10)
>>> y = np.round(np.sin(angle)*x).astype(int)
>>> [(x,y) for x, y in zip(x, y)]
[(0, 0), (1, 0), (2, 1), (3, 1), (4, 1), (5, 1), (6, 2), (7, 2), (8, 2), (9, 2)]


来源:https://stackoverflow.com/questions/45745930/how-to-get-value-of-pixels-which-are-at-a-certain-angle-from-another-pixel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!