gpt4 book ai didi

python - 如何在图像之间传递像素颜色和位置

转载 作者:行者123 更新时间:2023-12-02 10:48:00 25 4
gpt4 key购买 nike

我试图说明这张图片中的要点:

data.png

并将它们转移到此美国 map 轮廓上:

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行出现错误

我也尝试过将两个图像简单地加在一起,但是结果很奇怪。

我已经尝试了许多方法,但无法弄清楚如何使其工作。请帮忙!

提前致谢

最佳答案

在第一段代码中,您只需要交换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

关于python - 如何在图像之间传递像素颜色和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43464348/

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