首页 > 解决方案 > 如何在 OpenCV 上计算和排序 RGB 数据?

问题描述

RGB 数据。如何在 Python、OpenCV 上计算和排序它们

我想在 Python、OpenCV 上工作,这些步骤如下

1. Get the RGB data from pictures
2. Calculate the R*G*B on each pixel of the pictures
3. Sort the data by descending order and plot them on graph or csv
4. Get the max and min and medium of R*G*B

我可以处理步骤1。如下代码。但是,我不知道如何在 step2 之后编写程序 最好将数据保存为 csv 或 numpy 有人有想法吗?请帮我。如果您向我展示代码,那将非常有帮助。

import cv2
import numpy


im_f = np.array(Image.open('data/image.jpg'), 'f')
print(im[:, :]) 

标签: python-3.xnumpyopencv

解决方案


最好将内存中的数据保存为numpy数组。cv2.imread此外,使用而不是最终Image.open必须将其转换为来读取图像np.array

对于绘图,matplotlib可以使用。

OpenCV以下是如何使用和numpy来实现上述过程matplotlib

import numpy as np
import cv2, sys
import matplotlib.pyplot as plt

#Read image
im_f = cv2.imread('data/image.jpg')

#Validate image
if im_f is None:
    print('Image Not Found')
    sys.exit();

#Cast to float type to hold the results
im_f = im_f.astype(np.float32)


#Compute the product of channels and flatten the result to get 1D array
product = (im_f[:,:,0] * im_f[:,:,1] * im_f[:,:,2]).flatten()

#Sort the flattened array and flip it to get elements in descending order
product = np.sort(product)[::-1]

#Compute the min, max and median of product
pmin, pmax , pmed = np.amin(product), np.amax(product), np.median(product)

print('Min = ' + str(pmin))
print('Max = ' + str(pmax))
print('Med = ' + str(pmed))

#Show the sorted array
plt.plot(product)
plt.show()

在 Ubuntu 16.04 上使用 Python 3.5.2、OpenCV 4.0.1、numpy 1.15.4 和 matplotlib 3.0.2 进行了测试。


推荐阅读