我想从我的福禄克机器人那里得到一个图像并确定我图像中每个像素的颜色。然后,如果像素大部分是红色,则将其更改为完全绿色。如果像素大部分为绿色,请将其更改为完全蓝色。如果像素主要是蓝色,则将其更改为完全红色。这是我能够做到的,但我无法让它工作以获得我必须改变的图像。没有语法错误,它只是语义我遇到了麻烦。我正在使用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
答案 0 :(得分:13)
我假设你正在尝试使用Image
模块。这是一个例子:
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上运行此操作,我得到输出:
>>> 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
编辑: 为了做你想做的事,我会尝试这样的事情
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)
答案 1 :(得分: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):
我还建议你使用load(),因为它要快得多:
pix = im.load()
print pix[x, y]
pix[x, y] = value
答案 2 :(得分:2)
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)
答案 3 :(得分:0)
在Gizmo的回答中添加一些评论。这样:
px = im.load()
current_color = (px[i, j])
可能比这更快:
picture.getpixel( (x,y) )
另外,请务必使用:
picture.putdata(colors)
而不是循环中的这个:
picture.putpixel( (x,y), new_color)
答案 4 :(得分:0)
我使用的是python 3.6.4和Pillow 5.0.0。 Gizmo的代码片段对我不起作用。经过一番努力,我创建了一个固定的片段:
import numpy as np
from itertools import cycle, compress
startList = list(range(0, 3000))
startNpArray = np.linspace(0,2999,3000,dtype=np.int)
def WithNumpy(seq, keep, skip):
return seq.reshape((-1, keep+skip))[:,:keep+1].flatten()
def WithItertools(seq, keep, skip):
criteria = cycle([True]*keep + [False]* skip)
return list(compress(seq, criteria))
%timeit WithNumpy(startListNp, 10, 20)
>>> 2.59 µs ± 48.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit WithItertools(startList, 10, 20)
>>> 33.5 µs ± 911 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)