I created a list of RGB values for an image (let's say it's 3D_image, composed of 3D_image_slice). I want to extract the unique RGB values from it, but I'm running into problems.
rgb_values_unique = []
for 3D_image_slice in 3D_image:
for y in range(3D_image_slice.shape[0]):
for x in range(3D_image_slice.shape[1]):
if 3D_image_slice[y, x] not in rgb_values_unique:
rgb_values_unique.append(3D_image_slice[y, x])
I was thinking of using np.unique, but that doesn't apply to lists. Is there another way to find unique values within a list?
CodePudding user response:
You have a couple of easy options; one is to create a unique list of strings (I don't love this since it changes the datatype, but it's look something like this):
rgb_values_unique = set()
for 3D_image_slice in 3D_image:
for y in range(3D_image_slice.shape[0]):
for x in range(3D_image_slice.shape[1]):
rgb_values_unique.add("-".join(3D_image_slice[y, x])
print(rgb_values_unique)
# {"r0-g0-b0", "r1-g1-b1", ...}
#which you could convert back into numbers like this:
result = [[int(j) for j in i.split("-")] for i in rgb_values_unique]
What I'd probably do is leverage the uniqueness of a dictionary:
rgb_values_unique = {}
for 3D_image_slice in 3D_image:
for y in range(3D_image_slice.shape[0]):
for x in range(3D_image_slice.shape[1]):
r,g,b = 3D_image_slice[y, x]
rgb_values_unique .setdefault(r, {}).setdefault(g, []).append(b)
print(rgb_values_unique)
# {r0: {g0: [b0, b1, b2]}, {g1: ...
Which you can then turn into a unique listing as follows:
result = [(r,g,b) for r,v in rgb_values_unique.items() for g, b_list in v.items() for b in b_list]
CodePudding user response:
u can use sets to save only unique values:
rgb_values_unique = {}
for 3D_image_slice in 3D_image:
for y in range(3D_image_slice.shape[0]):
for x in range(3D_image_slice.shape[1]):
rgb_values_unique |= 3D_image_slice[y, x]