1

I'm using python and I was trying to do intensity transformation an image without numpy. So on the process, I need to log() the pixel of the image with math.log() but it looks like math.log() can't process an array like numpy did.

Should I do manual loop or is there any alternative?

Here's some code :

import cv2 as cv
import numpy as np
import math

img = cv.imread("272.jpg", cv.IMREAD_GRAYSCALE)

print(img)
# Output :
# array([[ 80,  72,  58, ...,  74,  77,  82],
#      [ 65,  59,  50, ...,  87,  88,  91],
#      [ 50,  47,  43, ..., 120, 117, 117],
#      ...,
#      [168, 158, 144, ...,  44,  52,  65],
#      [168, 157, 142, ...,  69,  74,  85],
#      [170, 156, 138, ...,  92,  94, 100]], dtype=uint8)

print(np.log(img))
# this works

print(math.log(img))
# error
panji gemilang
  • 759
  • 2
  • 10
  • 25

1 Answers1

1

By running math.log() on a list element you will get the following error: TypeError: only size-1 arrays can be converted to Python scalars, i.g., size-1 arrays is refer to one element of you multidimensional array. For example, map.log(img[0][0]) works since is one elements, therefore if you want to calculate the log, on math lib you must loop over with a maximum complexity of O(N^2). Python solve this problem by list comprehension, below code show one possible solution to you problem (although, you can explore more faster solution):

import cv2 as cv
import numpy as np
import math

img = cv.imread("272.jpg", cv.IMREAD_GRAYSCALE)

img_log = [[math.log(j) for j in img[i]] for i in range(len(img))]

print(img_log)
Marukox
  • 91
  • 2
  • 7
  • 1
    O(N^2) ?? Where N is what? Generally, you would care about the total number of items in the array, in which case, it is O(N) – juanpa.arrivillaga Sep 25 '19 at 06:36
  • It is true, we could flatten the vector image and in that case we will required a only one loop or O(N). However, since we are performing the loop over a image which dimension its structures is a nested list(array inside array) the [Time Complexity for Nested Loop](https://stackoverflow.com/questions/526728/time-complexity-of-nested-for-loop). However,I mentioned as **maximum complexity** which i.e. should be said as worst-case. – Marukox Sep 25 '19 at 07:00
  • No, the nested loop doesnt matter, it is not O(N^2) its O(N), the loops are not the same. The worst case is still the same as the best case here anyway, so that is irrelevant. You don;'t need to flatten it. Big-Oh doesn't mean how many loops are required... (Note, this is a classic interview gotcha: give you an example like this and asking you about the time complexity and seeing if you understand that it is actually linear not quadratic on the size of the input) – juanpa.arrivillaga Sep 25 '19 at 07:04