更改图片中的随机像素,python
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了更改图片中的随机像素,python,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2583字,纯文字阅读大概需要4分钟。
内容图文
![更改图片中的随机像素,python](/upload/InfoBanner/zyjiaocheng/744/bc196930fbf34cf9bd274f22af5c7f72.jpg)
我想编写一个函数,在这张图片的天空中创建一个随机数(在m和n之间,包括m和n)(http://tinypic.com/r/34il9hu/6).我希望星星应该由一个白色像素或一个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)
我不知道我在做什么:(
解决方法:
这似乎是尝试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')
现在我们有超像素,我们可以通过每个超像素来做分类更容易一些.你可以在这里使用一些花哨的分类,但是这个例子很简单,蓝天,让我们手工完成.
# 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)
内容总结
以上是互联网集市为您收集整理的更改图片中的随机像素,python全部内容,希望文章能够帮你解决更改图片中的随机像素,python所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。