Oli*_*ver 4 python random image pixels
我想编写一个函数,该函数将在这张图片(http://tinypic.com/r/34il9hu/6)的天空中创建一个随机数(在 m 和 n 之间,包括在内)星星。我希望星星应该由单个白色像素或由 4 个相邻白色像素组成的正方形随机组成。我也不想在树枝、月亮或鸟上放置一个“星星”(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)
Run Code Online (Sandbox Code Playgroud)
我不知道我在做什么:(
这看起来是尝试超像素的一个很好的例子,由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')
Run Code Online (Sandbox Code Playgroud)

现在我们有了超像素,我们可以通过按超像素进行分类来更轻松地进行分类。你可以在这里使用一些花哨的分类,但这个例子很简单,天空偏蓝,让我们手工完成。
# 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)
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
6373 次 |
| 最近记录: |