2017-04-18 74 views
1

我想取分這個圖像間的像素顏色和位置:如何傳輸圖像

data.png

,並將它們轉移到美國的這一地圖的輪廓:

us_outline.png

但我正在努力。

我想用一種方法,從'data.png'中讀取非綠色像素的顏色和座標位置,將它們存儲在列表中,然後將這些像素放置到'us_outline.png'基於他們的位置。

這裏是我的代碼至今:

#IMPORTS 
from __future__ import division 
import math 
import numpy as np 
from PIL import Image 
import matplotlib.pyplot as mplot 

#List of pixels from data.png 
pixels = [] 

height = 140 
width = 200 

#Read in data from data.png 
data = Image.open("data.png") 
data = data.convert('RGB') 

for row in range(0,height): #loops over the number of rows in the image 
    for col in range(0,width): # loops over the number of columns in the current row 
     r,g,b = data.getpixel((row,col)) 
     rgb = [] 
     rgb.append(r) 
     rgb.append(g) 
     rgb.append(b) 
     if rgb != [0,255,0]: 
      pixels.append(rgb) 

但這樣做在一個錯誤的結果:IndexError:圖像索引超出範圍

我也試過這樣:

#Convert to float32 format 
data_image = np.float32(data) 

#Reads in data points from data.png and appends them to a list 
for row in range(len(data_image)): #loops over the number of rows in the image 
    for col in range(len(data_image[row])): # loops over the number of columns in the current row 
     pixel = data_image[row][col] #Assigns pixel at row and column to a variable 
     if pixel != [0,255,0,255]: #If pixel is not green (a.k.a it is a data point) 
      pixels.append(pixel) #Set key to the location of pixel and set value to pixel color 

#Read in data from us_outline.png  
img2 = Image.open("us_outline.png") 
usmap = img2.load() 
#Convert to float32 format 
usmap_image = np.float32(usmap) 

#Writes data from pixels list to US map 
for row in range(len(usmap_image)): #loops over the number of rows in the image 
    for col in range(len(usmap_image[row])): # loops over the number of columns in the current row 
     for pixel in range(len(pixels)): 
      if pixels[row][col] == usmap_image[row][col]: 
       usmap_image[row][col] = pixels[row][col] 

usmap_image = np.uint8(usmap_image) 

但這樣做會導致第21行和第22行出現錯誤

我也嘗試過簡單地添加將這兩幅圖像放在一起,但是這產生了一個奇怪的結果。

我已經嘗試了很多方法,我無法弄清楚如何讓它工作。請幫忙!

在此先感謝

回答

0

在你的第一段代碼,你只需要更換rowcol在像素正確讀取。 18號線成爲

r,g,b = data.getpixel((col, row)) 

否則,下面這段代碼實現你的目標,是一個比較簡潔:

import numpy as np 
import matplotlib.pyplot as plt 

# find indices of non-green pixels 
data = plt.imread('data.png') 
green = np.zeros_like(data) 
green[:,:,1] = 1. # plt.imread for some bizarre reason returns rgb values between 0.-1. for the given pngs, not 0-255! 
x, y = np.where(np.any(data != green, axis=-1)) 

# plot non-green pixels on us outline 
us = plt.imread('us_outline.png') 
us[x,y] = data[x,y] 

plt.imshow(us) 
plt.show() 

enter image description here