2017-05-12 19 views
0

我建我的形象與cv2.THRESH_BINARY和功能如何用python製作二進制圖像?

RET,im_thresh = cv2.threshold(gray_image,40,255, cv2.THRESH_BINARY)

但白棋必須1與我的程序一起工作。

爲了幫助我做:

height = int(np.size(im_thresh, 0)) 
width = int(np.size(im_thresh, 1)) 

for x in range(height): 
    for y in range(width): 
     if im_thresh[x,y]==255: 
      im_thresh[x,y] = 1 

我的問題:有什麼辦法在Python更快做到這一點?

回答

1

嘗試使用布爾值索引來獲取和設置數組的值,從而避免嵌套for循環。

import numpy as np 
from numpy import random 

# Generating an image of values between 1 and 255. 
im_thresh = random.randint(1,256, (64,64)) 

# Set anything less than 255 to 0. Unnecessary if cv2 does this during threshold. 
# Must go before the operation below in order not to set all values to 0. 
im_thresh[im_thresh<255] = 0 

# Set all values at indices where the array equals 255 to 1. 
im_thresh[im_thresh==255] = 1