Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to apply sin() to all elements in an opencv Mat

Tags:

opencv

I have an opencv Mat, how can I apply sin() to all of its elements? Is it necessary to use a loop to get each element and calculate the sin one by one? Regards.

like image 910
beaver Avatar asked Nov 19 '25 04:11

beaver


1 Answers

I'm using python and using numpy so can do:

>>> import cv
>>> import numpy as np
>>> im = cv.LoadImageM("aaa.jpg")
>>> np.sin(im)
array([[[ 0.36319944,  0.46771851,  0.99646664],
        [ 0.98024565, -0.49104786,  0.46771851],
        [ 0.69605851, -0.9983471 , -0.49104786],
        ..., 
        [-0.58777064, -0.79041475,  0.60906792],
        [-0.79041475, -0.94252455,  0.36319944],
        [ 0.08839871, -0.58777064, -0.94252455]],
  etc...

Otherwise, it should be easy to adapt the below python code to create and use a look up table, cv.LUT:

import cv
import math

im = cv.LoadImageM("aaa.jpg")
dst = cv.CreateMat(im.height,im.width, cv.CV_32FC3)
lut_sin = cv.CreateMat(256, 1, cv.CV_32FC3)    

for i in xrange(256):     
    s = math.sin(i)
    cv.Set1D(lut_sin, i, (s,s,s,s))

cv.LUT(im,dst,lut_sin)

print cv.Get2D(dst,0,0)
#output, matches above:
(0.36319944262504578, 0.46771851181983948, 0.99646663665771484, 0.0)

For floating point data, you can use cv.PolarToCart:

>>> import cv
>>> im = cv.LoadImageM("aaa.jpg")
>>> im2 = cv.CreateMat(im.height, im.width, cv.CV_32FC3)
>>> cv.Convert(im,im2)
>>> sin_of_angle = cv.CreateMat(im.height, im.width, cv.CV_32FC3)
>>> cv.PolarToCart(None,im2,None,sin_of_angle,0)
>>> cv.Get1D(sin_of_angle,0)
(0.36319947242736816, 0.46771851181983948, 0.99646669626235962, 0.0)
>>> cv.Get1D(sin_of_angle,1)
(0.98024564981460571, -0.49104788899421692, 0.46771851181983948, 0.0)

You can use this to easily get the cos values as well. You can switch the last parameter to True for Radians.

like image 190
fraxel Avatar answered Nov 21 '25 08:11

fraxel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!