Reputation: 105
I am trying to sum up the greyscale pixel values of a greyscale image "1.jpg" for each vertical columns of pixels in the image.
Here is the code:
import cv2
img = cv2.imread("1.jpg", 0)
for i in range (img.shape[0]):
aaa = img[i]
print aaa
Doing this i get something like
aaa = [1,2,3] [2,3,4] [3,4,5] [4,5,6] .....
Now how do I sum up the array to get:
bbb = [6, 9, 12, 15, ....]
If I do:
import cv2
img = cv2.imread("1.jpg", 0)
for i in range (img.shape[0]):
aaa = img[i]
bbb = sum(aaa, 0)
print bbb
I get:
6
9
12
15
.
..
...
but thats not what I need !!!
UPDATE : Solved
Was finally able to do it by this:
import cv2
bbb = []
img = cv2.imread("1.jpg", 0)
for i in range (img.shape[0]):
bbb.append(sum(img[i]))
Upvotes: 0
Views: 3239
Reputation: 464
If you get array like :
[1,2,3]
[2,3,4]
[3,4,5]
[4,5,6]
then to sum up the array and to store it into a different list, try this code:
import cv2
img = cv2.imread("1.jpg", 0)
final_list = []
for i in range (img.shape[0]):
final_list.append(reduce(lambda x,y: x+y, img[i]))
print final_list
Upvotes: 0
Reputation: 174
Fastest way among all answers perhaps, try using the numpy package side by side. as follows :
import cv2
import numpy as np
img = cv2.imread('your_image_file')
sum_cols = np.sum(img,axis=1)
sum_cols = np.sum(img,axis=1) #if the image is a color image.
This works, and sums along the second axis, ie the column sum for each row and each color channel.
Upvotes: 1
Reputation: 8999
This should do it (untested). Note that img.shape[1]
gives the number of image columns.
import cv2
results = []
img = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE)
for col in range(img.shape[1]):
results.append(sum(img[col]))
Upvotes: 0
Reputation: 12168
you should put aaa in a container, like a list or set
aaa = []
for i in range (img.shape[0]):
aaa.append(img[i])
print aaa
or
aaa = [ i for i in range (img.shape[0])]
aaa = [[1,2,3],[2,3,4],[3,4,5],[4,5,6]]
[sum(a)for a in aaa]
out:
[6, 9, 12, 15]
Upvotes: 0