更改像素颜色Python

2024-06-28 19:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从我的fluke机器人那里得到一个图像,并确定图像中每个像素的颜色。然后,如果像素大部分是红色,则将其更改为完全绿色。如果像素大部分为绿色,则将其更改为完全蓝色。如果像素大部分为蓝色,则将其更改为完全红色。这是我能做的,但我不能让它发挥作用,以获得我必须改变的形象。没有语法错误,只是语义上的问题。我正在使用python。

我尝试的代码:

import getpixel
getpixel.enable(im)  
r, g, b = im.getpixel(0,0)  
print 'Red: %s, Green:%s, Blue:%s' % (r,g,b)

我还保存了图片,如下所示:

pic1 = makePicture("pic1.jpg"):
    for pixel in getpixel("pic1.jpg"):
        if pixel Red: %s:
           return Green:%s
        if pixel Green:%s: 
           return Blue:%s

Tags: 图像returnifgreenbluered像素蓝色
3条回答

你有错误:

# Get the size of the image

width, height = picture.size()

for x in range(0, width - 1):

        for y in range(0, height - 1):
  1. 括号是错误的!!省略它们。
  2. int不可iterable。

我还建议您使用load(),因为它更快:

pix = im.load()

print pix[x, y]

pix[x, y] = value

我假设您正在尝试使用Image模块。下面是一个例子:

from PIL import Image
picture = Image.open("/path/to/my/picture.jpg")
r,g,b = picture.getpixel( (0,0) )
print("Red: {0}, Green: {1}, Blue: {2}".format(r,g,b))

在这个image上运行这个,我得到输出:

>>> from PIL import Image
>>> picture = Image.open("/home/gizmo/Downloads/image_launch_a5.jpg")
>>> r,g,b = picture.getpixel( (0,0) )
>>> print("Red: {0}, Green: {1}, Blue: {2}".format(r,g,b))
Red: 138, Green: 161, Blue: 175

编辑: 做你想做的事我会试试这样的

from PIL import Image
picture = Image.open("/path/to/my/picture.jpg")

# Get the size of the image
width, height = picture.size()

# Process every pixel
for x in width:
   for y in height:
       current_color = picture.getpixel( (x,y) )
       ####################################################################
       # Do your logic here and create a new (R,G,B) tuple called new_color
       ####################################################################
       picture.putpixel( (x,y), new_color)
import cv2
import numpy as np

m =  cv2.imread("C:/../Sample Pictures/yourImage.jpg")

h,w,bpp = np.shape(m)

for py in range(0,h):
    for px in range(0,w):
#can change the below logic of rgb according to requirements. In this 
#white background is changed to #e8e8e8  corresponding to 232,232,232 
#intensity, red color of the image is retained.
        if(m[py][px][0] >200):            
            m[py][px][0]=232
            m[py][px][1]=232
            m[py][px][2]=232

cv2.imshow('matrix', m)
cv2.waitKey(0)
cv2.imwrite('yourNewImage.jpg',m)

相关问题 更多 >