Я кодирую последнюю часть программы кластеризации, я хочу проанализировать файл, например
--
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)
Я хочу сохранить всю эту информацию в разных классах, чтобы упростить обработку данных.
Вот мой код на питоне:
#!/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() для создания копии.
Спасибо!






Вам нужен атрибут экземпляра кластера с именем пиксели:
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) + ")")
Укс! Грубая ошибка с моей стороны, большое спасибо!
в
printCluster(),for px in pixels:должно бытьfor px in cl.pixels. Голосование за закрытие как опечатка.