Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a string to a numpy.zeros array [duplicate]

I've wrote code that goes through every pixel of a low-res image and stores the Hue, Saturation and Brightness levels (HSL) of each pixel in an array. Now, I would like to go through each of these HSL levels to determine what colour it is closest to and store this information into a new array. I have written this code:

arrayCol = np.zeros((sHeight,sWidth), dtype = str)
for y in range(sHeight):
    for x in range(sWidth):
        #for n in range(3):
        if arrayHSL[y][x][2] <= 10:
            if arrayHSL[y][x][2] <= 10:
                arrayCol[y][x] = 'blk'

print(arrayCol)

which assigns the pixel as 'blk' or 'black' if the lightness is below a certain threshold. However, upon printing and viewing the array, rather than showing 'blk' in the correct place, it only shows the first letter 'b' as seen in the output:

[['' '' '' '' '' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' '' 'b' '' '' '' '']
 ['' '' '' '' '' '' 'b' 'b' 'b' 'b' '' 'b' 'b' '' '' '' '' '' '' '']
 ['b' '' '' '' '' '' '' '' 'b' 'b' 'b' 'b' 'b' '' '' '' '' '' '' '']
 ['' '' '' '' '' '' '' '' '' 'b' 'b' 'b' '' '' '' '' '' '' '' '']
 ['' '' '' '' '' '' '' '' '' '' 'b' '' '' '' '' '' '' '' '' '']
 ['' '' '' '' '' 'b' '' '' '' '' '' 'b' '' '' '' '' '' '' '' '']
 ['' 'b' '' 'b' '' '' '' '' '' '' 'b' 'b' '' '' '' '' '' '' '' '']
 ['' '' '' 'b' '' 'b' '' '' '' '' '' '' '' 'b' '' '' '' '' '' '']
 ['' '' 'b' '' '' 'b' 'b' 'b' '' '' '' '' '' 'b' '' '' '' '' '' '']
 ['' '' 'b' 'b' '' 'b' '' 'b' '' 'b' 'b' '' 'b' 'b' '' '' '' '' '' '']
 ['b' '' 'b' '' 'b' '' '' '' 'b' 'b' '' 'b' 'b' 'b' '' '' '' 'b' '' '']
 ['b' 'b' 'b' 'b' 'b' 'b' 'b' '' '' '' '' 'b' '' 'b' '' '' '' '' '' '']

Changing the name 'blk' to something else, such as 'rlk' does the same, only showing just an 'r' instead. This would not be much of a problem but once I start implementing other colours such as blue or brown neither I nor Python will be able to differentiate them. So my question is how can I get the array to store the full names of the colours rather than just the first letter? Thanks

like image 875
tewi Avatar asked Nov 25 '25 08:11

tewi


1 Answers

If you type arrayCol.dtype it should print dtype('S1') meaning the strings of length 1. You can specify dtype='s256' for fixed length or dtype=object for abitrary length strings.

arrayCol = np.zeros((sHeight,sWidth), dtype = object)

like image 110
AmourK Avatar answered Nov 26 '25 22:11

AmourK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!