画像データを加工していた時に ???? となってしまった案件。
通常であれば
python
a = 1
b = a
a = a + 2
c = b
print ("ans ",a,b,c)
ans 3 1 1
となり問題ないが、
画像データ img_a を加工する際、加工前の状態を退避させる意図で
python
img_b = img_a
として画像データ img_b を加工したが、結果は画像データ img_a も加工されていた。
その時は????で、原因が解らなかったが、
画像データは配列なので、つぎの例と同じ動きをしていた。
python
a = [1,2]
b = a
a[0] = a[0] + 2
c = b
b[1] = b[1] + 5
print ("ans ",a,b,c)
ans [3, 7] [3, 7] [3, 7]
この様に、bも cも aと同じ実体を参照・処理している。
対策として
python
import numpy as np
a = [1,2]
b = np.array(a)
a[0] = a[0] + 2
c = np.array(b)
b[1] = b[1] + 5
print ("ans ",a,b,c)
ans [3, 2] [1 7] [1 2]
として解決した。
まあ、pythonではいろんな事が簡単に実現できるだけに、変数ひとつ取ってもいろんな事を考えなければならい様です。