programing

어떻게 RGB 이미지를 numpy 배열로 변환합니까?

lastcode 2023. 7. 16. 13:35
반응형

어떻게 RGB 이미지를 numpy 배열로 변환합니까?

저는 RGB 이미지를 가지고 있습니다.나는 그것을 numpy 배열로 변환하고 싶습니다.다음을 수행했습니다.

im = cv.LoadImage("abc.tiff")
a = numpy.asarray(im)

모양이 없는 배열을 만듭니다.나는 그것이 iplimage 객체라고 생각합니다.

새로운 OpenCV 파이썬 인터페이스를 사용할 수 있습니다(OpenCV 2.2 이후에 사용 가능한 것으로 알고 있습니다).기본적으로 Numpy 어레이를 사용합니다.

import cv2
im = cv2.imread("abc.tiff",mode='RGB')
print(type(im))

결과:

<type 'numpy.ndarray'>

PIL(Python Imaging Library)과 Numpy는 함께 잘 작동합니다.

저는 다음과 같은 기능을 사용합니다.

from PIL import Image
import numpy as np

def load_image( infilename ) :
    img = Image.open( infilename )
    img.load()
    data = np.asarray( img, dtype="int32" )
    return data

def save_image( npdata, outfilename ) :
    img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "L" )
    img.save( outfilename )

수신 데이터를 [0,255]에 클리핑하고 바이트로 변환한 다음 그레이스케일 이미지를 생성하기 때문에 'Image.fromarray'는 약간 보기 흉합니다.저는 주로 회색 옷을 입고 일합니다.

RGB 이미지는 다음과 같습니다.

out_img = Image.fromarray( ycc_uint8, "RGB" )
out_img.save( "ycc.tif" )

이에 대해 matplotlib을 사용할 수도 있습니다.

from matplotlib.image import imread

img = imread('abc.tiff')
print(type(img))

출력:<class 'numpy.ndarray'>

현재로서는 다음을 사용하는 것이 최선입니다.

img = cv2.imread(image_path)   # reads an image in the BGR format
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)   # BGR -> RGB

두고 보세요img다음 유형의 numpy 배열이 됩니다.

<class 'numpy.ndarray'>

답이 늦었지만, 저는 더 선호하게 되었습니다.imageio다른 대안에 대한 모듈

import imageio
im = imageio.imread('abc.tiff')

와 유사한cv2.imread()기본적으로 Numpy 배열을 생성하지만 RGB 형식입니다.

당신은 cv를 사용해야 합니다.cv 대신 ImageM을 로드합니다.이미지 로드:

In [1]: import cv
In [2]: import numpy as np
In [3]: x = cv.LoadImageM('im.tif')
In [4]: im = np.asarray(x)
In [5]: im.shape
Out[5]: (487, 650, 3)

다음을 사용하여 RGB 이미지의 numpy 배열을 쉽게 얻을 수 있습니다.numpy그리고.Image from PIL

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

im = Image.open('*image_name*') #These two lines
im_arr = np.array(im) #are all you need
plt.imshow(im_arr) #Just to verify that image array has been constructed properly

다음 구문을 사용하여 이미지를 로드합니다.

from keras.preprocessing import image

X_test=image.load_img('four.png',target_size=(28,28),color_mode="grayscale"); #loading image and then convert it into grayscale and with it's target size 
X_test=image.img_to_array(X_test); #convert image into array

David Pool의 답변을 사용할 때 회색 스케일 PNG 및 다른 파일과 함께 시스템 오류가 발생합니다.내 솔루션은 다음과(와)

import numpy as np
from PIL import Image

img = Image.open( filename )
try:
    data = np.asarray( img, dtype='uint8' )
except SystemError:
    data = np.asarray( img.getdata(), dtype='uint8' )

실제로 img.getdata()는 모든 파일에 사용할 수 있지만 속도가 느리기 때문에 다른 방법이 실패할 때만 사용합니다.

OpenCV 이미지 형식은 numpy 배열 인터페이스를 지원합니다.도우미 기능은 그레이스케일 또는 컬러 이미지를 지원하도록 만들 수 있습니다.이것은 BGR -> RGB 변환이 이미지 데이터의 전체 복사본이 아닌 numpy 슬라이스로 편리하게 수행될 수 있음을 의미합니다.

참고: 이는 스트라이드 트릭이므로 출력 배열을 수정하면 OpenCV 영상 데이터도 변경됩니다.복사본을 원하는 경우.copy()배열의 메소드!

import numpy as np

def img_as_array(im):
    """OpenCV's native format to a numpy array view"""
    w, h, n = im.width, im.height, im.channels
    modes = {1: "L", 3: "RGB", 4: "RGBA"}
    if n not in modes:
        raise Exception('unsupported number of channels: {0}'.format(n))
    out = np.asarray(im)
    if n != 1:
        out = out[:, :, ::-1]  # BGR -> RGB conversion
    return out

저는 또한 imageio를 채택했지만, 다음과 같은 기계들이 전처리와 후처리에 유용하다는 것을 알게 되었습니다.

import imageio
import numpy as np

def imload(*a, **k):
    i = imageio.imread(*a, **k)
    i = i.transpose((1, 0, 2))  # x and y are mixed up for some reason...
    i = np.flip(i, 1)  # make coordinate system right-handed!!!!!!
    return i/255


def imsave(i, url, *a, **k):
    # Original order of arguments was counterintuitive. It should
    # read verbally "Save the image to the URL" — not "Save to the
    # URL the image."

    i = np.flip(i, 1)
    i = i.transpose((1, 0, 2))
    i *= 255

    i = i.round()
    i = np.maximum(i, 0)
    i = np.minimum(i, 255)

    i = np.asarray(i, dtype=np.uint8)

    imageio.imwrite(url, i, *a, **k)

이유는 제가 이미지 표시뿐만 아니라 이미지 처리를 위해 numpy를 사용하고 있기 때문입니다.이를 위해 unt8s는 어색하기 때문에 0부터 1까지의 부동소수점 값으로 변환합니다.

이미지를 저장할 때 범위를 벗어나는 값을 직접 잘라내야 한다는 것을 알게 되었습니다. 그렇지 않으면 출력이 회색으로 표시됩니다.(회색 출력은 [0, 256]을 벗어난 전체 범위를 범위 내에 있는 값으로 압축한 결과입니다.)

제가 댓글에서 언급한 또 다른 이상한 점들도 몇 가지 있었습니다.

우리는 오픈 CV2의 다음 기능을 사용하여 BGR 2 RGB 포맷을 변환할 수 있습니다.

RBG_Image = cv2.cvtColor(Image, cv.COLOR_BGR2RGB)

Keras 사용:

from keras.preprocessing import image
  
img = image.load_img('path_to_image', target_size=(300, 300))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])

이미지를 numpy 배열에 로드하는 옵션의 타이밍을 맞춰 보십시오. 유사합니다.가!plt.imread간단하면서도 신속하게

def time_this(function, times=100):
    cum_time = 0
    for t in range(times):
        st = time.time()
        function()
        cum_time += time.time() - st
    return cum_time / times

import matplotlib.pyplot as plt
def load_img_matplotlib(img_path):
    return plt.imread(img_path)

import cv2
def load_img_cv2(img_path):
    return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)

from PIL import Image
import numpy as np
def load_img_pil(img_path):
    img = Image.open(img_path)
    img.load()
    return np.asarray( img, dtype="int32" )

if __name__=='__main__':
    img_path = 'your_image_path'
    for load_fn in [load_img_pil, load_img_cv2, load_img_matplotlib]:
        print('-'*20)
        print(time_this(lambda: load_fn(img_path)), 10000)

결과:

--------------------
0.0065201687812805175 10000  PIL, as in [the second answer][1]https://stackoverflow.com/a/7769424/16083419)
--------------------
0.0053211402893066405 10000  CV2
--------------------
0.005320906639099121 10000  matplotlib

당신은 다음 방법을 시도할 수 있습니다.여기 문서에 대한 링크가 있습니다.

tf.keras.preprocessing.image.img_to_array(img, data_format=None, dtype=None)
from PIL import Image
img_data = np.random.random(size=(100, 100, 3))
img = tf.keras.preprocessing.image.array_to_img(img_data)
array = tf.keras.preprocessing.image.img_to_array(img)

언급URL : https://stackoverflow.com/questions/7762948/how-to-convert-an-rgb-image-to-numpy-array

반응형