简体   繁体   中英

How to calculate and sort RGB data on OpenCV?

RGB data. How to calculate and sort them on Python, OpenCV

I want to work on Python, OpenCV these below steps

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

I could handle that the step1. as below code. However, I don't know how to write a program after step2 It's better to save the data as csv or numpy Does anybody have an idea? Please help me. it would be very helpful if you show me the code.

import cv2
import numpy


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

It is better to keep data in-memory as numpy array. Also, read image using cv2.imread rather than Image.open if it has to be converted to np.array eventually.

For plotting, matplotlib can be used.

Here is how the above mentioned process can be achieved using OpenCV , numpy and 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()

Tested with Python 3.5.2, OpenCV 4.0.1, numpy 1.15.4, and matplotlib 3.0.2 on Ubuntu 16.04.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM