Reputation: 103
I am trying to find out if a certain pixel of an image has more of a Red Green or Blue value. I tried this code below:
im = Image.open("image.png")
x = 32
y = 32
pixel = im.load()
rgb = pixel[x,y]
rgb = int(rgb)
if rgb[0] > rgb[1,2]:
print("Red")
elif rgb[1] > rgb[0,2]:
print("Green")
elif rgb[2] > rgb[0,1]:
print("Blue")
But its giving me this Error:
File "d:\path\app.py", line 11, in <module>
rgb = int(rgb)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
Please let me know what I'm doing wrong or if there's a better way of doing this!
Thanks
-Daniel
Upvotes: 0
Views: 703
Reputation: 1586
What you are doing wrong here is that you are passing a tuple
in the int()
function which returns a TypeError
.
A better way is to use Opencv for getting the values of R, G and B at your given (x, y)
import cv2
im = cv2.imread("image.png")
x, y = 32, 32
#get r, g and b values at (x, y)
r, g, b = im[x, y]
print(f"Pixel at ({x}, {y}) - Red: {r}, Green: {g}, Blue: {b}")
#then do your comparison
#following is an example
if (r>=g) and (r>=b):
print("Red")
elif (g>=r) and (g>=b):
print("Green")
else:
print("Blue")
Upvotes: 0
Reputation:
You can simply do:
red_image = Image.open("image.png")
red_image_rgb = red_image.convert("RGB")
rgb_pixel_value = red_image_rgb.getpixel((10,15))
if rgb_pixel_value[0]>rgb_pixel_value[1] and rgb_pixel_value[0]>rgb_pixel_value[2]:
print("Red")
elif rgb_pixel_value[0]<rgb_pixel_value[2] and <rgb_pixel_value[1]<rgb_pixel_value[2]:
print("Blue")
else:
print("Green")
Here is an interactive program:
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
root=tk.Tk()
def select_image():
s=filedialog.askopenfilename(filetypes=(("PNG",'*.png'),("JPEG",'*.jpg')))
if s!='':
global red_image
red_image = Image.open(s)
image1=ImageTk.PhotoImage(file=s)
lbl1.config(image=image1)
lbl1.image=image1
root.bind("<Motion>",check_pixel)
def check_pixel(event):
red_image_rgb = red_image.convert("RGB")
rgb_pixel_value = red_image_rgb.getpixel((event.x,event.y))
lbl2.config(text=f"Red: {rgb_pixel_value[0]} Green: {rgb_pixel_value[1]} Blue: {rgb_pixel_value[2]}")
if rgb_pixel_value[0]>rgb_pixel_value[1] and rgb_pixel_value[0]>rgb_pixel_value[2]:
lbl3.config(text="Red",fg="Red")
elif rgb_pixel_value[0]<rgb_pixel_value[2]and rgb_pixel_value[1]<rgb_pixel_value[2]:
lbl3.config(text="Blue",fg="Blue")
else:
lbl3.config(text="Green",fg="green")
button1=tk.Button(root,text='Select Image',command=select_image)
button1.pack()
lbl1=tk.Label(root)
lbl1.pack()
lbl2=tk.Label(root,text="Red: Green: Blue:")
lbl2.pack(side=tk.BOTTOM)
lbl3=tk.Label(root)
lbl3.pack()
root.mainloop()
Upvotes: 1