我正在撰寫集群程式的最后一部分,我想決議一個像
--
COLOR
-
POINT COLOR
...
在哪里
COLOR = (R,G,B)
POINT = (X,Y)
例子:
--
(255,0,4)
-
(0,0) (255,0,4)
(0,1) (255,0,4)
(0,2) (255,0,4)
(0,3) (255,0,4)
--
(32,32,12)
-
(1,0) (156,0,42)
(1,1) (156,0,42)
(1,2) (156,0,42)
(1,3) (156,0,42)
我想將所有這些資訊保存在不同的類中,以便更輕松地處理資料。
這是我在python中的代碼:
#!/usr/bin/env python3
import sys
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Color:
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Pixel:
def __init__(self, point, color):
self.point = point
self.color = color
class Cluster:
def __init__(self, meanColor, pixels):
self.meanColor = meanColor
self.pixels = pixels
def printCluster(cl):
print("---------------")
print("(" str(cl.meanColor.r) "," str(cl.meanColor.g) "," str(cl.meanColor.b) ")")
print("I have " str(len(pixels)) " pixels.")
for px in pixels:
print("(" str(px.point.x) "," str(px.point.y) ") (" str(px.color.r) "," str(px.color.g) "," str(px.color.b) ")")
def printClusters(clusters):
for cl in clusters:
printCluster(cl)
def getColor(line):
r = int(line.split(',')[0][1:])
g = int(line.split(',')[1])
b = int(line.split(',')[2][:-1])
color = Color(r,g,b)
return (color)
file = open(sys.argv[1], 'r')
meanColor = None
clusters = []
cluster = ""
pixels = []
import copy
count = 0
file.readline()
line = file.readline().rstrip('\n')
meanColor = getColor(line)
file.readline()
while True:
count = 1
line = file.readline().rstrip('\n')
if (line == "--"):
pixelsCopy = list(pixels)
cluster = Cluster(meanColor, pixelsCopy)
printClusters(clusters)
printCluster(cluster)
clusters.append(cluster)
pixels = []
printCluster(cluster)
line = file.readline().rstrip('\n')
meanColor = getColor(line)
file.readline()
elif (line and line != "--"):
print("-------------------------------")
printClusters(clusters)
print("line: ~" line "~")
x = int(line.split()[0].split(',')[0][1:])
y = int(line.split()[0].split(',')[1][:-1])
print("x: " str(x))
print("y: " str(y))
point = Point(x,y)
r = int(line.split()[1].split(',')[0][1:])
g = int(line.split()[1].split(',')[1])
b = int(line.split()[1].split(',')[2][:-1])
print("r: " str(r))
print("g: " str(g))
print("b: " str(b))
color = Color(r,g,b)
pixels.append(Pixel(point, color))
if not line:
pixelsCopy = list(pixels)
cluster = Cluster(meanColor, pixelsCopy)
clusters.append(cluster)
#printCluster(cluster)
break
printClusters(clusters)
出于某種原因,在 while 回圈之后,當我列印所有集群物件時,我看到所有物件都包含相同的像素串列,我嘗試使用 deepcopy、[:] 和 list() 進行復制,但沒有任何意義。我不知道我的錯誤在哪里,我也在重置為 [] 后列印集群,我看到它像參考串列一樣保存,但我不知道為什么我使用 list() 來制作副本。
謝謝!
uj5u.com熱心網友回復:
您需要集群實體的名為像素的屬性:
def printCluster(cl):
print("---------------")
print("(" str(cl.meanColor.r) "," str(cl.meanColor.g) "," str(cl.meanColor.b) ")")
print("I have " str(len(pixels)) " pixels.")
for px in cl.pixels:
print("(" str(px.point.x) "," str(px.point.y) ") (" str(px.color.r) "," str(px.color.g) "," str(px.color.b) ")")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471057.html
上一篇:如何將其轉換為dict
