python numpy遍历_Python 3:我试图通过使用np.array遍历所有像...

在直接回答您的问题时,y轴首先在numpy数组中给出,然后是x轴,因此要交换索引.

不那么直接,你会发现Python中的for循环非常慢,你通常最好使用numpy矢量化操作.此外,您经常会发现在HSV colourspace中更容易找到绿色阴影.

让我们从HSL色轮开始:

并假设你想把所有的果岭变成黑色.因此,从维基百科页面看,与绿色对应的Hue是120度,这意味着您可以这样做:

#!/usr/local/bin/python3

import numpy as np

from PIL import Image

# Open image and make RGB and HSV versions

RGBim = Image.open("image.png").convert('RGB')

HSVim = RGBim.convert('HSV')

# Make numpy versions

RGBna = np.array(RGBim)

HSVna = np.array(HSVim)

# Extract Hue

H = HSVna[:,:,0]

# Find all green pixels, i.e. where 100 < Hue < 140

lo,hi = 100,140

# Rescale to 0-255, rather than 0-360 because we are using uint8

lo = int((lo * 255) / 360)

hi = int((hi * 255) / 360)

green = np.where((H>lo) & (H

# Make all green pixels black in original image

RGBna[green] = [0,0,0]

count = green[0].size

print("Pixels matched: {}".format(count))

Image.fromarray(RGBna).save('result.png')

这使:

这是一个稍微改进的版本,保留了alpha /透明度,并匹配红色像素以获得额外的乐趣:

#!/usr/local/bin/python3

import numpy as np

from PIL import Image

# Open image and make RGB and HSV versions

im = Image.open("image.png")

# Save Alpha if present, then remove

if 'A' in im.getbands():

savedAlpha = im.getchannel('A')

im = im.convert('RGB')

# Make HSV version

HSVim = im.convert('HSV')

# Make numpy versions

RGBna = np.array(im)

HSVna = np.array(HSVim)

# Extract Hue

H = HSVna[:,:,0]

# Find all red pixels, i.e. where 340 < Hue < 20

lo,hi = 340,20

# Rescale to 0-255, rather than 0-360 because we are using uint8

lo = int((lo * 255) / 360)

hi = int((hi * 255) / 360)

red = np.where((H>lo) | (H

# Make all red pixels black in original image

RGBna[red] = [0,0,0]

count = red[0].size

print("Pixels matched: {}".format(count))

result=Image.fromarray(RGBna)

# Replace Alpha if originally present

if savedAlpha is not None:

result.putalpha(savedAlpha)

result.save('result.png')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值