加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:25:43 所属栏目:Python 来源:网络整理
导读:我想编写一个函数,在这张图片的天空中创建一个随机数(在m和n之间,包括m和n)( http://tinypic.com/r/34il9hu/6).我希望星星应该由一个白色像素或一个4个相邻白色像素的正方形组成.我也不想在树枝,月亮或鸟上放置一个“星”(1像素)虽然 我怎么能在python中这样
我想编写一个函数,在这张图片的天空中创建一个随机数(在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,:] = 255
        img[x+1,:] = 255
        img[x,y-1,y+1,:] = 255

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读