2017-04-21 1 views
1

그래서 색상 이미지 배치가 있고 그레이 스케일을 만들고 싶습니다. 유일한 문제는 모양이 [batch_size, channels, height, width]이고 때로는 [batch_size, height, width, channels] 인 경우도 있습니다. 컬러 이미지 배치 (두 가지 모양 중 아무리 상관없이)를 사용하고 모양이 회색 모양 일괄 처리 [batch_size, height, width, channels] (채널은 물론 1)을 제공하는 기능이 필요합니다.파이썬에서 색상에서 그레이 스케일로 이미지를 일괄 처리합니다.

은 지금까지 나는이 기능을 가지고 : 나는 배치를 재구성하는 for 루프의 끝에 np.vstack을하고 생각하고

from scipy import misc 

def color_to_grayscale(image_batch, dim_order='NHWC'): 

    grayscale_batch = np.array() 

    if dim_order='NCHW': 
    image_batches = np.transpose(image_batch, [0, 2, 3, 1]) 
    else: 
    image_batches = image_batch 

    for idx in range(image_batches[0].shape): 
    image = image_batches[idx, :, :, :] 
    grayscale = np.zeros((image.shape[0], image.shape[1])) 

    for rownum in range(len(image)): 
     for colnum in range(len(image[rownum])): 
      grayscale[rownum][colnum] = np.average(image[rownum][colnum]) 

    grayscale = np.array(grayscale, dtype="float32") 
    grayscale = grayscale.reshape((grayscale.shape[0], grayscale.shape[1], 1)) 

    grayscale_batch = np.stack(grayscale, grayscale_batch) 

return grayscale_batch 

을하지만 지저분한 보인다. 또한 위의 두 경우 (치수)를 고려하지 않았습니다.

아이디어가 있으십니까?

편집 : 작업 할 것으로 예상되는 코드로 업데이트되었습니다 (그래도 여전히 그렇지 않습니다).

+0

'idx in range (image_batches [0] .shape)'에 대해 확실합니까? –

+0

아니, 나에게 거기에 오류를 제공합니다. – Qubix

+0

'image_batches.shape [0]' –

답변

0

당신은 당신이 사용할 수있는 권리 모양의 배열을 가지고 당신의 채널을 통해 numpy.mean()

# axis=-1 is channels, keepdims is optional 
greyscale_image_batch = numpy.mean(image_batch, axis=-1, keepdims=True) 
image_batch.shape    # [batch_size, height, width, channels] 
greyscale_image_batch.shape # [batch_size, height, width, 1] 

를 사용, 스택 또는 아무것도, 어떤 루프를 수행 할 필요가 없습니다 transpose() :

if image_batch.shape[1] == 3: 
    image_batch = image_batch.transpose([0, 2, 3, 1]) 
+0

numpy.mean을 사용하여 답의 첫 번째 부분을 가져올 지 확신 할 수 없습니다. 나는 또한 그것을 얻을 수있는 완성 된 것으로 나의 기능을 업데이트했다. – Qubix

+0

실행 해 보셨습니까? –

+0

그리고 작동 했습니까? –

관련 문제