最快的解决方案
让我们考虑一个使用cv2.split 的函数,我们知道它的效率非常低,我们可以继续调整图像的某个部分的大小或裁剪,然后对其进行计算。在我必须使用cv2.split 计算图像色彩的情况下,我继续调整图像大小并裁剪图像以使cv2.split 工作。
- 可以通过调整大小来执行更快、更合理的
cv2.split 计算
代码
def image_colorfulness(self,image):
# split the image into its respective RGB components
(B, G, R) = cv2.split(image.astype("float"))
print(f'Split Image to B G R {(B, G, R)}')
# compute rg = R - G
rg = np.absolute(R - G)
print(f'Computed RG to {rg}')
# compute yb = 0.5 * (R + G) - B
yb = np.absolute(0.5 * (R + G) - B)
# compute the mean and standard deviation of both `rg` and `yb`
print('Performing Absolute')
(rbMean, rbStd) = (np.mean(rg), np.std(rg))
(ybMean, ybStd) = (np.mean(yb), np.std(yb))
# combine the mean and standard deviations
print('Performing Standard Deviation')
stdRoot = np.sqrt((rbStd ** 2) + (ybStd ** 2))
meanRoot = np.sqrt((rbMean ** 2) + (ybMean ** 2))
# derive the "colorfulness" metric and return it
return stdRoot + (0.3 * meanRoot)
def crop_square(self, img, size, interpolation=cv2.INTER_AREA):
h, w = img.shape[:2]
min_size = np.amin([h,w])
# Centralize and crop
crop_img = img[int(h/2-min_size/2):int(h/2+min_size/2), int(w/2-min_size/2):int(w/2+min_size/2)]
resized = cv2.resize(crop_img, (size, size), interpolation=interpolation)
return resized
img = cv2.imread(image_path)
resize_img = self.crop_square(img, 300)
## perform your calculation on the resized_img and continue with the original img then
colorness = self.image_colorfulness(resize_img)
仅调整大小
如果您不想裁剪而只调整图像大小,可以通过查看square_crop 函数中的这行代码来实现。
resized = cv2.resize(crop_img, (size, size), interpolation=interpolation)
测试结果
之前
- 我测试了一个
5.0 MB *.PNG 图像,然后在cv2.split 中使用标准图像输入,它在8 分钟内处理。
之后
在调整图像大小后,它在调整大小的图像上缩小为0.001 ms。
标准图片
调整大小的图像