简体   繁体   中英

How to write Python console output (Image to RGB matrix) into a txt file?

I am new to Python. I am using 3.8.3 version. My code is:

if __name__ == '__main__':
    import imageio
    import matplotlib.pyplot as plt
    
    pic = imageio.imread('Photo_Vikash_pandey.jpg')
    plt.figure(figsize = (15,15))

    plt.imshow(pic)
    
    print('Value of only R channel {}'.format(pic[ 100, 50, 0]))
    print('Value of only G channel {}'.format(pic[ 100, 50, 1]))
    print('Value of only B channel {}'.format(pic[ 100, 50, 2]))

I can print the RGB values of any desired pixel. But how do I output the complete RGB matrix that corresponds to the entire image. The image size in pixels is 200x150. I wish to output in a .txt file.

The problem is that an image is a 3D matrix, ie in your case it's a 200x150x3 matrix (3 being the color channels, RGB). So, you could do something like:

import cv2
import numpy as np

image = cv2.imread("path_to_your_image", 1)
for i in range(0,3):
    np.savetxt(f"image_channel_{i}.txt", image[:,:,i])
  

Basically, this way you're considering each time the matrix of values for each color channel, which is a normal 2D matrix, and you can write each of them to a separate file. You do that by using the notation:

image[:,:,i]

which means, taking all rows and columns of the matrix (the : in between parenthesis) for the index i, which changes in the loop between 0 and 2 (telling you all of this because you said you're new to Python).

Or, you can write the 3 matrices one after another in the same file, as you prefer.
The main point is that you can't write the whole 3D matrix to a file as it is.

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