george joker
george joker

Reputation: 11

Can i iterate over an image while ignoring black pixels?

I have a segmented image using SLIC from scipy and for every superpixel i get an image where only that superpixel is colored and the rest of the image is black. I want to iterate ONLY on the colored pixels from that one superpixel. I have tried using for loop like this:

for i in range(0,mask.shape[0]):
        for j in range(0,mask.shape[1]):
            x,y,z = each_segment[i][j] #gets the pixel RGB value
            unique_pixel_array = [x,y,z] #creates a vector that holds those values for each pixel
            if (unique_pixel_array != [0,0,0]):
                print(unique_pixel_array)

This method is working however it is very inefficient considerin it is iterating over the entire image, and if i have a big image it will take a very long time to process for every superpixel. Is there a faster and more efficient way to do this?

I will attach the whole code below , maybe you will get a better sense of the whole thing.

from skimage.segmentation import slic
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
import matplotlib.pyplot as plt
import numpy as np
import cv2


img = cv2.imread("image.png")
segments = slic(img_as_float(img),n_segments= 7 ,slic_zero=True,sigma =5)
fig = plt.figure("Superpixels -- %d segments" % (22))
ax = fig.add_subplot(1, 1, 1)
ax.imshow(mark_boundaries(img, segments))
plt.axis("off")
plt.show()

for (sp,segVal) in enumerate (np.unique(segments)):

    mask = np.zeros(img.shape[:2],dtype = "uint8")
    mask[segments == segVal] = 255
    each_segment = cv2.bitwise_and(img,img,mask=mask)

    for i in range(0,mask.shape[0]):
        for j in range(0,mask.shape[1]):      
            x,y,z = each_segment[i][j]
            unique_pixel_array = [x,y,z]
            print(unique_pixel_array)



    cv2.imshow("Mask", mask)
    cv2.imshow("Applied", cv2.bitwise_and(img, img, mask = mask))
    cv2.waitKey(0)

Upvotes: 0

Views: 370

Answers (0)

Related Questions