質問編集履歴

2

きれいに整形

2020/08/03 05:19

投稿

RyosukeSHIBATA
RyosukeSHIBATA

スコア11

test CHANGED
File without changes
test CHANGED
@@ -42,6 +42,374 @@
42
42
 
43
43
  for dish in ind:
44
44
 
45
+ axis.add_patch(dish.fig)#<-----ここでエラーが発生
46
+
47
+ axis.axis("off")
48
+
49
+ plt.savefig('tmp.png')
50
+
51
+ fig.delaxes(axis)
52
+
53
+ plt.clf()
54
+
55
+ plt.cla()
56
+
57
+ plt.close()
58
+
59
+ del axis
60
+
61
+ gray_img = cv2.imread('tmp.png')
62
+
63
+ ind.img = gray_img
64
+
65
+ ret, dishes_area_image = cv2.threshold(gray_img, 200, 255, cv2.THRESH_BINARY)#図形がある
66
+
67
+ dishes_area = cv2.countNonZero(cv2.bitwise_not(cv2.cvtColor(dishes_area_image, cv2.COLOR_RGB2GRAY)))
68
+
69
+ cv2.imwrite('dishes_area.png',dishes_area_image)
70
+
71
+ ret, dishes_overlap_area_image = cv2.threshold(gray_img, 100, 255, cv2.THRESH_BINARY)#重なってて黒い
72
+
73
+ cv2.imwrite('dishes_overlap_area.png',dishes_overlap_area_image)
74
+
75
+ dishes_overlap_area = cv2.countNonZero(cv2.bitwise_not(cv2.cvtColor(dishes_overlap_area_image, cv2.COLOR_RGB2GRAY)))
76
+
77
+ overlap_per = 1 - dishes_overlap_area/dishes_area
78
+
79
+
80
+
81
+ return evaluation * overlap_per
82
+
83
+ ```
84
+
85
+
86
+
87
+ # プログラム全体
88
+
89
+ ```
90
+
91
+ import random
92
+
93
+ import numpy as np
94
+
95
+ from operator import attrgetter
96
+
97
+ import csv
98
+
99
+ import matplotlib
100
+
101
+ import matplotlib.pyplot as plt
102
+
103
+ import cv2
104
+
105
+ #
106
+
107
+
108
+
109
+
110
+
111
+ def main():
112
+
113
+ n_gene = 4 # The number of genes.
114
+
115
+ n_ind = 300 # The number of individuals in a population.
116
+
117
+ CXPB = 0.5 # The probability of crossover.
118
+
119
+ MUTPB = 0.2 # The probability of individdual mutation.
120
+
121
+ MUTINDPB = 0.05 # The probability of gene mutation.
122
+
123
+ NGEN = 40 # The number of generation loop.
124
+
125
+ dish_types= DishTypes()
126
+
127
+ dish_types.load_file()
128
+
129
+ random.seed(64)
130
+
131
+ # --- Step1 : Create initial generation.
132
+
133
+ pop = create_pop(n_ind, n_gene, dish_types)
134
+
135
+ set_fitness(evalOneMax, pop)
136
+
137
+ best_ind = max(pop, key=attrgetter("fitness"))
138
+
139
+
140
+
141
+ # --- Generation loop.
142
+
143
+ print("Generation loop start.")
144
+
145
+ print("Generation: 0. Best fitness: " + str(best_ind.fitness))
146
+
147
+ fig_save(best_ind, '{:0=5}'.format(0))
148
+
149
+ for g in range(NGEN):
150
+
151
+
152
+
153
+ # --- Step2 : Selection.
154
+
155
+ offspring = selTournament(pop, n_ind, tournsize=3)
156
+
157
+
158
+
159
+ # --- Step3 : Crossover.
160
+
161
+ crossover = []
162
+
163
+ for child1, child2 in zip(offspring[::2], offspring[1::2]):# (偶数個目,奇数個目)で子孫を作成
164
+
165
+ if random.random() < CXPB:
166
+
167
+ child1, child2 = cxTwoPointCopy(child1, child2)
168
+
169
+ # child1.fitness = None
170
+
171
+ # child2.fitness = None
172
+
173
+ crossover.append(child1)
174
+
175
+ crossover.append(child2)
176
+
177
+
178
+
179
+ offspring = crossover[:]
180
+
181
+
182
+
183
+ # --- Step4 : Mutation.
184
+
185
+ mutant = []
186
+
187
+ for mut in offspring:
188
+
189
+ if random.random() < MUTPB:
190
+
191
+ mut = mutFlipBit(dish_types, mut, indpb=MUTINDPB)
192
+
193
+ # mut.fitness = None
194
+
195
+ mutant.append(mut)
196
+
197
+
198
+
199
+ offspring = mutant[:]
200
+
201
+
202
+
203
+ # --- Update next population.
204
+
205
+ pop = offspring[:]
206
+
207
+ set_fitness(evalOneMax, pop)
208
+
209
+
210
+
211
+ # --- Print best fitness in the population.
212
+
213
+ best_ind = max(pop, key=attrgetter("fitness"))
214
+
215
+ print("Generation: " + str(g + 1) + ". Best fitness: " + str(best_ind.fitness))
216
+
217
+ fig_save(best_ind, dish_types, '{:0=5}'.format(g + 1))
218
+
219
+ print("Generation loop ended. The best individual: ")
220
+
221
+ print(best_ind)
222
+
223
+
224
+
225
+
226
+
227
+ class DishTypes:
228
+
229
+ def __init__(self):
230
+
231
+ self.num=0
232
+
233
+ self.type=[]
234
+
235
+ self.size=[]
236
+
237
+ self.name=[]
238
+
239
+ self.calorie=[]
240
+
241
+ self.protein=[]
242
+
243
+ self.lipid=[]
244
+
245
+ self.carbohydrate=[]
246
+
247
+ self.calcium=[]
248
+
249
+ self.price=[]
250
+
251
+ self.tray_size=np.array([370, 260])
252
+
253
+ def load_file(self):
254
+
255
+ with open('dish.csv') as f:
256
+
257
+ reader = csv.reader(f)
258
+
259
+ for row in reader:
260
+
261
+ self.name.append(row[0])
262
+
263
+ self.type.append(int(row[1]))
264
+
265
+ self.size.append(int(row[2]))
266
+
267
+ self.calorie.append(float(row[3]))
268
+
269
+ self.protein.append(float(row[4]))
270
+
271
+ self.lipid.append(float(row[5]))
272
+
273
+ self.carbohydrate.append(float(row[6]))
274
+
275
+ self.calcium.append(float(row[7]))
276
+
277
+ self.price.append(float(row[8]))
278
+
279
+ self.num = len(self.name)
280
+
281
+
282
+
283
+
284
+
285
+ class Dish:
286
+
287
+ def __init__(self, id, dish_types):
288
+
289
+ self.figure_type=dish_types.type[id]
290
+
291
+ self.fig=create_figure(dish_types.type[id],dish_types.size[id],dish_types.tray_size)
292
+
293
+ self.name=dish_types.name[id]
294
+
295
+ self.calorie=dish_types.calorie[id]
296
+
297
+ self.protein=dish_types.protein[id]
298
+
299
+ self.lipid=dish_types.lipid[id]
300
+
301
+ self.carbohydrate=dish_types.carbohydrate[id]
302
+
303
+ self.calcium=dish_types.calcium[id]
304
+
305
+ self.price=dish_types.price[id]
306
+
307
+
308
+
309
+
310
+
311
+ class IndividualTray(list):
312
+
313
+ """Container of a individual."""
314
+
315
+ fitness = None
316
+
317
+ img = None
318
+
319
+
320
+
321
+ def __new__(cls, a):
322
+
323
+ return list.__new__(cls, a)
324
+
325
+
326
+
327
+
328
+
329
+ def create_figure(fig_type, size, tray_size):
330
+
331
+ x = random.randrange(size, tray_size[0] - size)
332
+
333
+ y = random.randrange(size, tray_size[1] - size)
334
+
335
+ if fig_type == 0:
336
+
337
+ return matplotlib.patches.Rectangle((x, y), size, size, facecolor='black', alpha=0.5)
338
+
339
+ if fig_type == 1:
340
+
341
+ return matplotlib.patches.Circle((x, y), radius=size, facecolor='black', alpha=0.5)
342
+
343
+
344
+
345
+
346
+
347
+ def create_ind(n_gene, dish_types):
348
+
349
+ """Create a individual."""
350
+
351
+ return IndividualTray([Dish(random.randint(0, dish_types.num-1), dish_types) for i in range(n_gene)])
352
+
353
+
354
+
355
+
356
+
357
+ def create_pop(n_ind, n_gene, dish_types):
358
+
359
+ """Create a population."""
360
+
361
+ pop = []
362
+
363
+ for i in range(n_ind):
364
+
365
+ ind = create_ind(n_gene, dish_types)
366
+
367
+ pop.append(ind)
368
+
369
+ return pop
370
+
371
+
372
+
373
+
374
+
375
+ def set_fitness(eval_func, pop):
376
+
377
+ """Set fitnesses of each individual in a population."""
378
+
379
+ for i, fit in zip(range(len(pop)), map(eval_func, pop)):
380
+
381
+ pop[i].fitness = fit
382
+
383
+
384
+
385
+
386
+
387
+ def evalOneMax(ind):
388
+
389
+ """Objective function."""
390
+
391
+ evaluation = 0
392
+
393
+ for dish in ind:
394
+
395
+ evaluation += dish.calorie
396
+
397
+ # TODO:グラフ領域を設定
398
+
399
+
400
+
401
+ #TODO:いい感じにトレーのサイズを外から引数として撮ってくるやり方がわからない直接書いた
402
+
403
+
404
+
405
+ tray_size = np.array([370, 260])
406
+
407
+ fig = plt.figure()
408
+
409
+ axis = fig.add_subplot(1, 1, 1, xlim=tray_size[0], ylim=tray_size[1], aspect='equal')
410
+
411
+ for dish in ind:
412
+
45
413
  axis.add_patch(dish.fig)
46
414
 
47
415
  axis.axis("off")
@@ -80,476 +448,108 @@
80
448
 
81
449
  return evaluation * overlap_per
82
450
 
451
+
452
+
453
+
454
+
455
+ def selTournament(pop, n_ind, tournsize):
456
+
457
+ """Selection function."""
458
+
459
+ chosen = []
460
+
461
+ for i in range(n_ind):
462
+
463
+ aspirants = [random.choice(pop) for j in range(tournsize)]#適当にtournsizeこだけ個体を選ぶ
464
+
465
+ chosen.append(max(aspirants, key=attrgetter("fitness")))#fitness属性の一番大きいものを選ぶ
466
+
467
+ return chosen
468
+
469
+
470
+
471
+
472
+
473
+ def cxTwoPointCopy(ind1, ind2):
474
+
475
+ """Crossover function."""
476
+
477
+ size1 = len(ind1)
478
+
479
+ size2 = len(ind2)
480
+
481
+ tmp1 = ind1.copy()
482
+
483
+ tmp2 = ind2.copy()
484
+
485
+ cxpoint1 = int(size1/2)
486
+
487
+ cxpoint2 = int(size2/2)
488
+
489
+ tmp1, tmp2 = tmp2[:cxpoint2].copy()+tmp1[cxpoint1:].copy(), tmp1[:cxpoint1].copy()+tmp2[cxpoint2:].copy()
490
+
491
+ return tmp1, tmp2
492
+
493
+
494
+
495
+
496
+
497
+ def mutFlipBit(dish_types, ind, indpb):
498
+
499
+ """Mutation function."""
500
+
501
+ tmp = ind.copy()
502
+
503
+ for i in range(len(ind)):
504
+
505
+ if random.random() < indpb:
506
+
507
+ rand = random.randint(0, 2)
508
+
509
+ # 増やす
510
+
511
+ if rand == 0:
512
+
513
+ tmp[i] = ind.append(Dish(random.randint(0, dish_types.num-1), dish_types))
514
+
515
+ break
516
+
517
+ # へらす
518
+
519
+ if rand == 1:
520
+
521
+ tmp[i] = ind.pop(random.randint(0,len(ind)-1))
522
+
523
+ break
524
+
525
+ # 変える
526
+
527
+ if rand == 2:
528
+
529
+ randopos = random.randint(0, len(ind) - 1)
530
+
531
+ tmp[i] = ind.pop(randopos)
532
+
533
+ tmp[i] = ind.insert(randopos, random.randint(0, len(ind) - 1))
534
+
535
+ break
536
+
537
+ return tmp
538
+
539
+
540
+
541
+
542
+
543
+ def fig_save(ind, file_name):
544
+
545
+ cv2.imwrite(',/img/'+file_name+'.png', ind.img)
546
+
547
+
548
+
549
+ if __name__ == "__main__":
550
+
551
+ main()
552
+
553
+
554
+
83
555
  ```
84
-
85
-
86
-
87
- # プログラム全体
88
-
89
- ```
90
-
91
- import random
92
-
93
- import numpy as np
94
-
95
- from operator import attrgetter
96
-
97
- import csv
98
-
99
- import matplotlib
100
-
101
- import matplotlib.pyplot as plt
102
-
103
- import cv2
104
-
105
- #
106
-
107
-
108
-
109
-
110
-
111
- def main():
112
-
113
- n_gene = 4 # The number of genes.
114
-
115
- n_ind = 300 # The number of individuals in a population.
116
-
117
- CXPB = 0.5 # The probability of crossover.
118
-
119
- MUTPB = 0.2 # The probability of individdual mutation.
120
-
121
- MUTINDPB = 0.05 # The probability of gene mutation.
122
-
123
- NGEN = 40 # The number of generation loop.
124
-
125
- dish_types= DishTypes()
126
-
127
- dish_types.load_file()
128
-
129
- random.seed(64)
130
-
131
- # --- Step1 : Create initial generation.
132
-
133
- pop = create_pop(n_ind, n_gene, dish_types)
134
-
135
- set_fitness(evalOneMax, pop)
136
-
137
- best_ind = max(pop, key=attrgetter("fitness"))
138
-
139
-
140
-
141
- # --- Generation loop.
142
-
143
- print("Generation loop start.")
144
-
145
- print("Generation: 0. Best fitness: " + str(best_ind.fitness))
146
-
147
- fig_save(best_ind, '{:0=5}'.format(0))
148
-
149
- for g in range(NGEN):
150
-
151
-
152
-
153
- # --- Step2 : Selection.
154
-
155
- offspring = selTournament(pop, n_ind, tournsize=3)
156
-
157
-
158
-
159
- # --- Step3 : Crossover.
160
-
161
- crossover = []
162
-
163
- for child1, child2 in zip(offspring[::2], offspring[1::2]):# (偶数個目,奇数個目)で子孫を作成
164
-
165
- if random.random() < CXPB:
166
-
167
- child1, child2 = cxTwoPointCopy(child1, child2)
168
-
169
- # child1.fitness = None
170
-
171
- # child2.fitness = None
172
-
173
- crossover.append(child1)
174
-
175
- crossover.append(child2)
176
-
177
-
178
-
179
- offspring = crossover[:]
180
-
181
-
182
-
183
- # --- Step4 : Mutation.
184
-
185
- mutant = []
186
-
187
- for mut in offspring:
188
-
189
- if random.random() < MUTPB:
190
-
191
- mut = mutFlipBit(dish_types, mut, indpb=MUTINDPB)
192
-
193
- # mut.fitness = None
194
-
195
- mutant.append(mut)
196
-
197
-
198
-
199
- offspring = mutant[:]
200
-
201
-
202
-
203
- # --- Update next population.
204
-
205
- pop = offspring[:]
206
-
207
- set_fitness(evalOneMax, pop)
208
-
209
-
210
-
211
- # --- Print best fitness in the population.
212
-
213
- best_ind = max(pop, key=attrgetter("fitness"))
214
-
215
- print("Generation: " + str(g + 1) + ". Best fitness: " + str(best_ind.fitness))
216
-
217
- fig_save(best_ind, dish_types, '{:0=5}'.format(g + 1))
218
-
219
- print("Generation loop ended. The best individual: ")
220
-
221
- print(best_ind)
222
-
223
-
224
-
225
-
226
-
227
- class DishTypes:
228
-
229
- def __init__(self):
230
-
231
- self.num=0
232
-
233
- self.type=[]
234
-
235
- self.size=[]
236
-
237
- self.name=[]
238
-
239
- self.calorie=[]
240
-
241
- self.protein=[]
242
-
243
- self.lipid=[]
244
-
245
- self.carbohydrate=[]
246
-
247
- self.calcium=[]
248
-
249
- self.price=[]
250
-
251
- self.tray_size=np.array([370, 260])
252
-
253
- def load_file(self):
254
-
255
- with open('dish.csv') as f:
256
-
257
- reader = csv.reader(f)
258
-
259
- for row in reader:
260
-
261
- self.name.append(row[0])
262
-
263
- self.type.append(int(row[1]))
264
-
265
- self.size.append(int(row[2]))
266
-
267
- self.calorie.append(float(row[3]))
268
-
269
- self.protein.append(float(row[4]))
270
-
271
- self.lipid.append(float(row[5]))
272
-
273
- self.carbohydrate.append(float(row[6]))
274
-
275
- self.calcium.append(float(row[7]))
276
-
277
- self.price.append(float(row[8]))
278
-
279
- self.num = len(self.name)
280
-
281
-
282
-
283
-
284
-
285
- class Dish:
286
-
287
- def __init__(self, id, dish_types):
288
-
289
- self.figure_type=dish_types.type[id]
290
-
291
- self.fig=create_figure(dish_types.type[id],dish_types.size[id],dish_types.tray_size)
292
-
293
- self.name=dish_types.name[id]
294
-
295
- self.calorie=dish_types.calorie[id]
296
-
297
- self.protein=dish_types.protein[id]
298
-
299
- self.lipid=dish_types.lipid[id]
300
-
301
- self.carbohydrate=dish_types.carbohydrate[id]
302
-
303
- self.calcium=dish_types.calcium[id]
304
-
305
- self.price=dish_types.price[id]
306
-
307
-
308
-
309
-
310
-
311
- class IndividualTray(list):
312
-
313
- """Container of a individual."""
314
-
315
- fitness = None
316
-
317
- img = None
318
-
319
-
320
-
321
- def __new__(cls, a):
322
-
323
- return list.__new__(cls, a)
324
-
325
-
326
-
327
-
328
-
329
- def create_figure(fig_type, size, tray_size):
330
-
331
- x = random.randrange(size, tray_size[0] - size)
332
-
333
- y = random.randrange(size, tray_size[1] - size)
334
-
335
- if fig_type == 0:
336
-
337
- return matplotlib.patches.Rectangle((x, y), size, size, facecolor='black', alpha=0.5)
338
-
339
- if fig_type == 1:
340
-
341
- return matplotlib.patches.Circle((x, y), radius=size, facecolor='black', alpha=0.5)
342
-
343
-
344
-
345
-
346
-
347
- def create_ind(n_gene, dish_types):
348
-
349
- """Create a individual."""
350
-
351
- return IndividualTray([Dish(random.randint(0, dish_types.num-1), dish_types) for i in range(n_gene)])
352
-
353
-
354
-
355
-
356
-
357
- def create_pop(n_ind, n_gene, dish_types):
358
-
359
- """Create a population."""
360
-
361
- pop = []
362
-
363
- for i in range(n_ind):
364
-
365
- ind = create_ind(n_gene, dish_types)
366
-
367
- pop.append(ind)
368
-
369
- return pop
370
-
371
-
372
-
373
-
374
-
375
- def set_fitness(eval_func, pop):
376
-
377
- """Set fitnesses of each individual in a population."""
378
-
379
- for i, fit in zip(range(len(pop)), map(eval_func, pop)):
380
-
381
- pop[i].fitness = fit
382
-
383
-
384
-
385
-
386
-
387
- def evalOneMax(ind):
388
-
389
- """Objective function."""
390
-
391
- evaluation = 0
392
-
393
- for dish in ind:
394
-
395
- evaluation += dish.calorie
396
-
397
- # TODO:グラフ領域を設定
398
-
399
-
400
-
401
- #TODO:いい感じにトレーのサイズを外から引数として撮ってくるやり方がわからない直接書いた
402
-
403
-
404
-
405
- tray_size = np.array([370, 260])
406
-
407
- fig = plt.figure()
408
-
409
- axis = fig.add_subplot(1, 1, 1, xlim=tray_size[0], ylim=tray_size[1], aspect='equal')
410
-
411
- for dish in ind:
412
-
413
- axis.add_patch(dish.fig)
414
-
415
- axis.axis("off")
416
-
417
- plt.savefig('tmp.png')
418
-
419
- fig.delaxes(axis)
420
-
421
- plt.clf()
422
-
423
- plt.cla()
424
-
425
- plt.close()
426
-
427
- del axis
428
-
429
- gray_img = cv2.imread('tmp.png')
430
-
431
- ind.img = gray_img
432
-
433
- ret, dishes_area_image = cv2.threshold(gray_img, 200, 255, cv2.THRESH_BINARY)#図形がある
434
-
435
- dishes_area = cv2.countNonZero(cv2.bitwise_not(cv2.cvtColor(dishes_area_image, cv2.COLOR_RGB2GRAY)))
436
-
437
- cv2.imwrite('dishes_area.png',dishes_area_image)
438
-
439
- ret, dishes_overlap_area_image = cv2.threshold(gray_img, 100, 255, cv2.THRESH_BINARY)#重なってて黒い
440
-
441
- cv2.imwrite('dishes_overlap_area.png',dishes_overlap_area_image)
442
-
443
- dishes_overlap_area = cv2.countNonZero(cv2.bitwise_not(cv2.cvtColor(dishes_overlap_area_image, cv2.COLOR_RGB2GRAY)))
444
-
445
- overlap_per = 1 - dishes_overlap_area/dishes_area
446
-
447
-
448
-
449
- return evaluation * overlap_per
450
-
451
-
452
-
453
-
454
-
455
- def selTournament(pop, n_ind, tournsize):
456
-
457
- """Selection function."""
458
-
459
- chosen = []
460
-
461
- for i in range(n_ind):
462
-
463
- aspirants = [random.choice(pop) for j in range(tournsize)]#適当にtournsizeこだけ個体を選ぶ
464
-
465
- chosen.append(max(aspirants, key=attrgetter("fitness")))#fitness属性の一番大きいものを選ぶ
466
-
467
- return chosen
468
-
469
-
470
-
471
-
472
-
473
- def cxTwoPointCopy(ind1, ind2):
474
-
475
- """Crossover function."""
476
-
477
- size1 = len(ind1)
478
-
479
- size2 = len(ind2)
480
-
481
- tmp1 = ind1.copy()
482
-
483
- tmp2 = ind2.copy()
484
-
485
- cxpoint1 = int(size1/2)
486
-
487
- cxpoint2 = int(size2/2)
488
-
489
- tmp1, tmp2 = tmp2[:cxpoint2].copy()+tmp1[cxpoint1:].copy(), tmp1[:cxpoint1].copy()+tmp2[cxpoint2:].copy()
490
-
491
- return tmp1, tmp2
492
-
493
-
494
-
495
-
496
-
497
- def mutFlipBit(dish_types, ind, indpb):
498
-
499
- """Mutation function."""
500
-
501
- tmp = ind.copy()
502
-
503
- for i in range(len(ind)):
504
-
505
- if random.random() < indpb:
506
-
507
- rand = random.randint(0, 2)
508
-
509
- # 増やす
510
-
511
- if rand == 0:
512
-
513
- tmp[i] = ind.append(Dish(random.randint(0, dish_types.num-1), dish_types))
514
-
515
- break
516
-
517
- # へらす
518
-
519
- if rand == 1:
520
-
521
- tmp[i] = ind.pop(random.randint(0,len(ind)-1))
522
-
523
- break
524
-
525
- # 変える
526
-
527
- if rand == 2:
528
-
529
- randopos = random.randint(0, len(ind) - 1)
530
-
531
- tmp[i] = ind.pop(randopos)
532
-
533
- tmp[i] = ind.insert(randopos, random.randint(0, len(ind) - 1))
534
-
535
- break
536
-
537
- return tmp
538
-
539
-
540
-
541
-
542
-
543
- def fig_save(ind, file_name):
544
-
545
- cv2.imwrite(',/img/'+file_name+'.png', ind.img)
546
-
547
-
548
-
549
- if __name__ == "__main__":
550
-
551
- main()
552
-
553
-
554
-
555
- ```

1

きれいに整形

2020/08/03 05:19

投稿

RyosukeSHIBATA
RyosukeSHIBATA

スコア11

test CHANGED
File without changes
test CHANGED
@@ -6,7 +6,87 @@
6
6
 
7
7
  というエラーが起きて困っています.
8
8
 
9
+ # 問題箇所
10
+
11
+ https://stackoverrun.com/ja/q/12300089
12
+
13
+ こちらのリンクでplt.figureを複数設定して解決されている話はあるのですが,
14
+
15
+ 今のプログラムでうまくplt.figureを複数生成する方法が思いつきません.
16
+
17
+ ```
18
+
19
+ def evalOneMax(ind):
20
+
21
+ """Objective function."""
22
+
23
+ evaluation = 0
24
+
25
+ for dish in ind:
26
+
27
+ evaluation += dish.calorie
28
+
29
+ # TODO:グラフ領域を設定
30
+
31
+
32
+
33
+ #TODO:いい感じにトレーのサイズを外から引数として撮ってくるやり方がわからない直接書いた
34
+
35
+
36
+
37
+ tray_size = np.array([370, 260])
38
+
39
+ fig = plt.figure()
40
+
41
+ axis = fig.add_subplot(1, 1, 1, xlim=tray_size[0], ylim=tray_size[1], aspect='equal')
42
+
43
+ for dish in ind:
44
+
45
+ axis.add_patch(dish.fig)
46
+
47
+ axis.axis("off")
48
+
9
- '''
49
+ plt.savefig('tmp.png')
50
+
51
+ fig.delaxes(axis)
52
+
53
+ plt.clf()
54
+
55
+ plt.cla()
56
+
57
+ plt.close()
58
+
59
+ del axis
60
+
61
+ gray_img = cv2.imread('tmp.png')
62
+
63
+ ind.img = gray_img
64
+
65
+ ret, dishes_area_image = cv2.threshold(gray_img, 200, 255, cv2.THRESH_BINARY)#図形がある
66
+
67
+ dishes_area = cv2.countNonZero(cv2.bitwise_not(cv2.cvtColor(dishes_area_image, cv2.COLOR_RGB2GRAY)))
68
+
69
+ cv2.imwrite('dishes_area.png',dishes_area_image)
70
+
71
+ ret, dishes_overlap_area_image = cv2.threshold(gray_img, 100, 255, cv2.THRESH_BINARY)#重なってて黒い
72
+
73
+ cv2.imwrite('dishes_overlap_area.png',dishes_overlap_area_image)
74
+
75
+ dishes_overlap_area = cv2.countNonZero(cv2.bitwise_not(cv2.cvtColor(dishes_overlap_area_image, cv2.COLOR_RGB2GRAY)))
76
+
77
+ overlap_per = 1 - dishes_overlap_area/dishes_area
78
+
79
+
80
+
81
+ return evaluation * overlap_per
82
+
83
+ ```
84
+
85
+
86
+
87
+ # プログラム全体
88
+
89
+ ```
10
90
 
11
91
  import random
12
92
 
@@ -470,4 +550,6 @@
470
550
 
471
551
  main()
472
552
 
553
+
554
+
473
- '''
555
+ ```