Development Tip

Numpy 크기 조정 / 크기 조정 이미지

yourdevel 2021. 1. 6. 20:29
반응형

Numpy 크기 조정 / 크기 조정 이미지


이미지를 가져 와서 이미지의 크기를 변경하고 싶지만 numpy 배열입니다.

예를 들어 코카콜라 병 이미지가 있습니다. bottle-1

이것은 numpy 배열의 모양으로 변환되며 (528, 203, 3)두 번째 이미지의 크기로 크기를 조정하고 싶습니다. bottle-2

모양이 (140, 54, 3).

원본 이미지를 유지하면서 이미지 크기를 특정 모양으로 변경하려면 어떻게합니까? 다른 답변은 다른 모든 행 또는 세 번째 행을 제거하는 것이 좋지만 기본적으로 이미지 편집기를 사용하지만 Python 코드로 이미지를 축소하는 것입니다. numpy / SciPy에서이를 수행 할 라이브러리가 있습니까?


예, 설치 opencv(이미지 처리 및 컴퓨터 비전에 사용되는 라이브러리)하고 cv2.resize기능을 사용할 수 있습니다. 예를 들어 다음을 사용하십시오.

import cv2
import numpy as np

img = cv2.imread('your_image.jpg')
res = cv2.resize(img, dsize=(54, 140), interpolation=cv2.INTER_CUBIC)

여기 img반면, 원본 이미지가 포함 된 NumPy와 어레이, 따라서이다 res함유 NumPy와 배열 리사이즈 된 화상. 중요한 측면은 interpolation매개 변수입니다. 이미지 크기를 조정하는 방법에는 여러 가지가 있습니다. 특히 이미지를 축소하고 원본 이미지 의 크기가 크기가 조정 된 이미지의 배수 아니기 때문에 특히 그렇습니다. 가능한 보간 스키마는 다음과 같습니다.

  • INTER_NEAREST -가장 가까운 이웃 보간
  • INTER_LINEAR -쌍 선형 보간 (기본적으로 사용됨)
  • INTER_AREA-픽셀 영역 관계를 사용한 리샘플링. 무아레없는 결과를 제공하므로 이미지 데시 메이션에 선호되는 방법 일 수 있습니다. 그러나 이미지를 확대하면 INTER_NEAREST방법 과 비슷합니다 .
  • INTER_CUBIC -4x4 픽셀 이웃에 대한 쌍 입방 보간
  • INTER_LANCZOS4 -8x8 픽셀 이웃에 대한 Lanczos 보간

대부분의 옵션과 마찬가지로 모든 크기 조정 스키마에 대해 하나의 전략이 다른 전략보다 선호 될 수있는 시나리오가 있다는 점에서 "최상의"옵션은 없습니다.


이를 위해 numpy 만 사용하는 것이 가능할 수도 있지만이 작업은 내장되어 있지 않습니다. 즉, scikit-image(numpy에 구축 된)를 사용하여 이러한 종류의 이미지 조작을 수행 할 수 있습니다 .

Scikit-Image rescaling 문서는 여기에 있습니다 .

예를 들어 이미지로 다음을 수행 할 수 있습니다.

from skimage.transform import resize
bottle_resized = resize(bottle, (140, 54))

이것은 보간, 앤티 앨리어싱 등과 같은 것들을 처리 할 것입니다.


numpy머신 러닝 애플리케이션에서 사용하기 위해 배열 에서 이미지를 다운 샘플링하는 빠른 방법을 찾고있는 Google에서 여기에 오는 사람들을 위해 여기에서 채택한 초고속 방법이 있습니다 . 이 방법은 입력 차원이 출력 차원의 배수 인 경우에만 작동합니다.

다음 예제는 128x128에서 64x64로 다운 샘플링합니다 (쉽게 변경할 수 있음).

마지막 주문 채널

# large image is shape (128, 128, 3)
# small image is shape (64, 64, 3)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((output_size, bin_size, 
                                   output_size, bin_size, 3)).max(3).max(1)

채널 첫 주문

# large image is shape (3, 128, 128)
# small image is shape (3, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((3, output_size, bin_size, 
                                      output_size, bin_size)).max(4).max(2)

회색조 이미지의 3경우 다음 1과 같이 변경하십시오 .

채널 첫 주문

# large image is shape (1, 128, 128)
# small image is shape (1, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((1, output_size, bin_size,
                                      output_size, bin_size)).max(4).max(2)

이 방법은 최대 풀링에 해당하는 방법을 사용합니다. 내가 찾은 가장 빠른 방법입니다.


SciPy's imresize() method was another resize method, but it will be removed starting with SciPy v 1.3.0 . SciPy refers to PIL image resize method: Image.resize(size, resample=0)

size – The requested size in pixels, as a 2-tuple: (width, height).
resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.

Link here: https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize


import cv2
import numpy as np

image_read = cv2.imread('filename.jpg',0) 
original_image = np.asarray(image_read)
width , height = 452,452
resize_image = np.zeros(shape=(width,height))

for W in range(width):
    for H in range(height):
        new_width = int( W * original_image.shape[0] / width )
        new_height = int( H * original_image.shape[1] / height )
        resize_image[W][H] = original_image[new_width][new_height]

print("Resized image size : " , resize_image.shape)

cv2.imshow(resize_image)
cv2.waitKey(0)

Are there any libraries to do this in numpy/SciPy

Sure. You can do this without OpenCV, scikit-image or PIL.

Image resizing is basically mapping the coordinates of each pixel from the original image to its resized position.

Since the coordinates of an image must be integers (think of it as a matrix), if the mapped coordinate has decimal values, you should interpolate the pixel value to approximate it to the integer position (e.g. getting the nearest pixel to that position is known as Nearest neighbor interpolation).

All you need is a function that does this interpolation for you. SciPy has interpolate.interp2d.

You can use it to resize an image in numpy array, say arr, as follows:

W, H = arr.shape[:2]
new_W, new_H = (600,300)
xrange = lambda x: np.linspace(0, 1, x)

f = interp2d(xrange(W), xrange(H), arr, kind="linear")
new_arr = f(xrange(new_W), xrange(new_H))

Of course, if your image is RGB, you have to perform the interpolation for each channel.

If you would like to understand more, I suggest watching Resizing Images - Computerphile.

ReferenceURL : https://stackoverflow.com/questions/48121916/numpy-resize-rescale-image

반응형