简体   繁体   中英

How to add a value to all elements of a sliced 3D numpy array?

My Code:

img = np.asarray(ibuffer).copy()
imgb = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)
imgb[:,:,0] += bvalue
imgb = cv2.cvtColor(imgb,cv2.COLOR_LAB2BGR)
photo = Image.fromarray(imgb)
photo = resize(photo)
photo = ImageTk.PhotoImage(photo)
canvas.photo = photo
canvas.create_image(0,0,anchor="nw",image = photo)

I need to add the value of 'bvalue' variable to all the elements of the 1st dimension the imgb(3D numpy array). When I try this, I get the following error message:

Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\asaru\AppData\Local\Programs\Python\Python39\lib\tkinter_ init _.py", line 1884, in call return self.func(*args) File "e:\My Files\Project\Image Editor\Image Editor\test.py", line 134, in bright

imgb[:,:,0] += bvalue

numpy.core._exceptions._UFuncOutputCastingError: Cannot cast ufunc 'add' output from dtype('<U3') to dtype('uint8') with casting rule 'same_kind'

Check Numpy Dtypes . Your variable bvalue is of Unicode String type and variable imgb is unsigned int type. They cannot be added.

You're allowed to add ints to numpy.uint8. If you cast your bvalue to an int (and assuming that bvalue is something that can be cast to an int) then your code should work.

lab[:,:,0] += int(50.0)

The line above works for brightening the image. Be careful, since the channel is a uint8, it'll overflow if it goes over 255. If you go above that it'll wrap back around and continue on (255 + 11 = 10).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM