gpt4 book ai didi

python - 更改图片中的随机像素,python

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:35 24 4
gpt4 key购买 nike

我想编写一个函数,在这张图片 ( http://tinypic.com/r/34il9hu/6 ) 的天空中创建一个随机数(介于 m 和 n 之间,包括在内)的星星。我希望星星应该由单个白色像素或 4 个相邻白色像素的正方形随机组成。我也不想在 Twig 、月亮或鸟上放置一颗“星星”(1 像素)虽然

我如何在 python 中执行此操作?谁能帮忙?谢谢!

到目前为止我有这个:

到目前为止,我已经开始并得出了这个结论,但我不知道它是否正确,或者即使我走在正确的轨道上:

def randomStars(small, large):
import random
file = pickAFile()
pic = makePicture(myPic)
#x = random.randrange(getWidth(pic))
#y = random.randrange(getHeight(pic))
for pixel in pic.getAllPixels():
if random.random() < 0.25:
pixel.red = random.randint(256)
pixel.green = random.randint(256)
pixel.blue = random.randint(256)
show(pic)

我不知道我在做什么:(

最佳答案

这看起来是一个很好的例子来尝试 superpixels ,由 skimage 实现.您可能可以通过更简单的方式来解决您的问题。

import urllib
import random
import io
import matplotlib.pyplot as plt
import skimage.segmentation
import pandas

# Read the image
f = io.BytesIO(urllib.urlopen('http://oi46.tinypic.com/34il9hu.jpg').read())
img = plt.imread(f, format='jpg')

# Prefer to keep pixels together based on location
# But not too much, so we still get some branches.
superpixel = skimage.segmentation.slic(img, n_segments=200, ratio=20)
plt.imshow(superpixel%7, cmap='Set2')

Superpixels

现在我们有了超像素,我们可以通过对每个超像素进行分类来更容易地进行分类。你可以在这里使用一些花哨的分类,但这个例子很简单,天空是蓝色的,让我们手工来做。

# Create a data frame with the relative blueish of every super pixel

# Convert image to hsv
hsv = matplotlib.colors.rgb_to_hsv(img.astype('float32')/255)
# Define blueish as the percentage of pixels in the blueish range of the hue space
df =pandas.DataFrame({'superpixel':superpixel.ravel(),
'blue':((hsv[:,:,0] > 0.4) & (hsv[:,:,0]<0.8)).astype('float32').ravel(),
'value':hsv[:,:,2].ravel()})
grouped = df.groupby('superpixel').mean()
# Lookup the superpixels with the least blue
blue = grouped.sort('blue', ascending=True).head(100)
# Lookup the darkest pixels
light = grouped.sort('value', ascending=True).head(50)

# If superpixels are too dark or too blue, get rid of them
mask = (np.in1d(superpixel, light.index ).reshape(superpixel.shape) |
np.in1d(superpixel, blue.index ).reshape(superpixel.shape))

# Now we can put the stars on the blueish, not too darkish areas
def randomstar(img, mask):
"""random located star"""
x,y = random.randint(1,img.shape[0]-1), random.randint(1,img.shape[1]-1)
if not mask[x-1:x+1, y-1:y+1].any():
# color not so random
img[x,y,:] = 255
img[x-1,y,:] = 255
img[x+1,y,:] = 255
img[x,y-1,:] = 255
img[x,y+1,:] = 255

for i in range(100):
randomstar(img, mask)
plt.imshow(img)

stars in the sky

关于python - 更改图片中的随机像素,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15145046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com