Sep-24-2023, 12:53 PM
(This post was last modified: Sep-24-2023, 12:53 PM by deanhystad.)
What did you do to understand this problem before posting? Did you look at the shape of numpy_array? Did you read enough about numpy to know that they can be multidimensional?
numpy_arrray (a terrible variable name) will be a 3-dimensional array. You will know this if you look at the shape. The first dimension are rows in the image. The second dimension are pixels in the rows, and the third dimension are red, green, blue (, opacity) values for each pixel. In your code, i[0] is the first pixel in a row, not red. [i][1] and [i][2] are not python.
You could create an array of pixels by reshaping the array.
If all you want to know is if there is any non-white pixel in the image, I would forget about pixel values and test the individual components.
numpy_arrray (a terrible variable name) will be a 3-dimensional array. You will know this if you look at the shape. The first dimension are rows in the image. The second dimension are pixels in the rows, and the third dimension are red, green, blue (, opacity) values for each pixel. In your code, i[0] is the first pixel in a row, not red. [i][1] and [i][2] are not python.
You could create an array of pixels by reshaping the array.
pixels = np.array(Image.open("p2.bmp")) rows, columns, rgba = pixels.shape print(rows, columns, rgba pixels = np.reshape(pixels, (-1, rgba))Now you have an array of pixels, not an image. You can do this:
for pixel in pixels: r, g, b = pixelNow you learn your logic is wrong. RGB for cyan is (0, 255, 255). RGB for magenta is (255, 0, 255) RGB for yellow is (255, 255, 0). According to your program logic, cyan, magenta and yellow are all white. According to your logic, red, green and blue are also white. All of these colors have one or more components that == 255.
for pixel in pixels: r, g, b = pixel if r < 255 or g < 255 or b < 255: print(pixel)lThe description of your problem is unclear. Do you want a count of pixels, or is a single non-white pixel enough to satisfy the test? Do you care about the color of this pixel, or is it only important that it not be white?
If all you want to know is if there is any non-white pixel in the image, I would forget about pixel values and test the individual components.
import numpy as np from PIL import Image values = np.array(Image.open("test.png"))[:, :, :3].flatten() print(np.any(values < 255))Or
import numpy as np from PIL import Image image = Image.open("test.png") pixels = np.array(image) rgb_pixels = pixels[:, :, :3] # Throw away any opacity information. values = rgb_pixels.flatten() # Make a 1-dimensional array values_less_than_255 = values < 255 # array of bool. True if value < 255 any_value_less_than_255 = np.any(values_less_than_255) # Are any values < 255?Bitmaps don't have opacity information. If you are only ever going to test a bitmap file you can skip the slicing step.