I was just wondering if there is a way to speed up the performances of this for loops in Python.
I'm trying to process an image to get the color-moments without using libraries. It takes about 12sec to do the calculate_mean and calculate_standard_deviation functions for each part of the image.
import math
import cv2
import numpy as np
parts = 2
new_height = int(img.shape[0]/parts)
new_width = int(img.shape[1]/parts)
for i in range (0,img.shape[0],new_height):
for j in range(0,img.shape[1],new_width):
color_moments = [0,0,0,0,0,0,0,0,0]
cropped_image = img[i:i+new_height,j:j+new_width]
yuv_image = cv2.cvtColor(cropped_image,cv2.COLOR_BGR2YUV)
Y,U,V = cv2.split(yuv_image)
pixel_image_y = np.array(Y).flatten()
pixel_image_u = np.array(U).flatten()
pixel_image_v = np.array(V).flatten()
calculate_mean(pixel_image_y,pixel_image_u,pixel_image_v,color_moments)
calculate_standard_deviation(pixel_image_y, pixel_image_u, pixel_image_v, color_moments)
And this are the two functions:
def calculate_mean(pixel_image_y,pixel_image_u,pixel_image_v,color_moments):
for p in pixel_image_y:
color_moments[0]+=(1/(new_height*new_width))*int(p)
for p in pixel_image_u:
color_moments[1]+=(1/(new_height*new_width))*int(p)
for p in pixel_image_v:
color_moments[2]+=(1/(new_height*new_width))*int(p)
def calculate_standard_deviation(pixel_image_y,pixel_image_u,pixel_image_v,color_moments):
temp = [0,0,0]
for p in pixel_image_y:
temp[0]+=(p-color_moments[0])**2
color_moments[3] = math.sqrt((1/(new_height*new_width))*temp[0])
for p in pixel_image_u:
temp[1]+=(p-color_moments[1])**2
color_moments[4] = math.sqrt((1/(new_height*new_width))*temp[1])
for p in pixel_image_v:
temp[2]+=(p-color_moments[2])**2
color_moments[5] = math.sqrt((1/(new_height*new_width))*temp[2])
color_moments
reset for each iteration, because that is not clear from the code here. Why not just usenp.mean
andnp.std
\$\endgroup\$