I'm trying to implement an algorithm to verify the 4 neighbout (up, down, left and right) pixels of an RGB image, if all pixel RGB values are equal I mark an pixel in the output image as 1, otherwise it will be 0. The non vectorized implementation is:
def set_border_interior(img):
img_rows = img.shape[0]
img_cols = img.shape[1]
res = np.zeros((img_rows,img_cols))
for row in xrange(1,img_rows-1):
for col in xrange(1,img_cols-1):
data_b = set()
data_g = set()
data_r = set()
up = row - 1
down = row + 1
left = col - 1
right = col + 1
data_b.add(img.item(row,col,0))
data_g.add(img.item(row,col,1))
data_r.add(img.item(row,col,2))
data_b.add(img.item(up,col,0))
data_g.add(img.item(up,col,1))
data_r.add(img.item(up,col,2))
data_b.add(img.item(down,col,0))
data_g.add(img.item(down,col,1))
data_r.add(img.item(down,col,2))
data_b.add(img.item(row,left,0))
data_g.add(img.item(row,left,1))
data_r.add(img.item(row,left,2))
data_b.add(img.item(row,right,0))
data_g.add(img.item(row,right,1))
data_r.add(img.item(row,right,2))
if (len(data_b) == 1) and (len(data_g) == 1) and (len(data_r) == 1):
res.itemset(row,col, False)
else:
res.itemset(row,col, True)
return res
This non vectorized way, but it is really slow (even using img.item to read data and img.itemset to set new values). Is there a better way to implement this in Numpy (or scipy)?
Leaving the border aside, where your function is not well defined anyway, you could do the following:
import numpy as np
import matplotlib.pyplot as plt
rows, cols = 480, 640
rgb_img = np.zeros((rows, cols, 3), dtype=np.uint8)
rgb_img[:rows//2, :cols//2] = 255
center_slice = rgb_img[1:-1, 1:-1]
left_slice = rgb_img[1:-1, :-2]
right_slice = rgb_img[1:-1, 2:]
up_slice = rgb_img[:-2, 1:-1]
down_slice = rgb_img[2:, 1:-1]
all_equal = (np.all(center_slice == left_slice, axis=-1) &
np.all(center_slice == right_slice, axis=-1) &
np.all(center_slice == up_slice, axis=-1) &
np.all(center_slice == down_slice, axis=-1))
plt.subplot(211)
plt.imshow(rgb_img, interpolation='nearest')
plt.subplot(212)
plt.imshow(all_equal, interpolation='nearest')
plt.show()
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.