taotoolkit 1.1.7__tar.gz → 1.1.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taotoolkit
3
- Version: 1.1.7
3
+ Version: 1.1.8
4
4
  Summary: Tao ToolKit
5
5
  Author-email: taotaoli <taotaoli@asrmicro.com>
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "taotoolkit"
7
- version = "1.1.7"
7
+ version = "1.1.8"
8
8
  description = "Tao ToolKit"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -39,7 +39,7 @@ from .tao_camDvt import camDvtMain as camDvtMain, printHelp as camDvtHelp, CamDv
39
39
 
40
40
  from .asrVrf import Vrf
41
41
 
42
- __version__ = "1.1.7"
42
+ __version__ = "1.1.8"
43
43
 
44
44
  __all__ = [
45
45
  "debugCtrl",
@@ -67,10 +67,10 @@ class VrfTail:
67
67
  meta[5] = self.AWBGainB
68
68
  meta[6] = self.AWBGainG
69
69
  meta[7] = self.AWBGainR
70
- meta[8] = self.AWBGainB
71
- meta[9] = self.AWBGainG
72
- meta[10] = self.AWBGainG
73
- meta[11] = self.AWBGainR
70
+ meta[8] = self.AWBGainWriteB
71
+ meta[9] = self.AWBGainWriteGb
72
+ meta[10] = self.AWBGainWriteGr
73
+ meta[11] = self.AWBGainWriteR
74
74
  meta[12] = self.BLC10b + np.uint16(self.BayerOrder) * 256
75
75
  meta[13] = self.BLC12b
76
76
  high = self.Reserve[1::2].astype(np.uint16) << 8 # 左移 8 位相当于 * 256
@@ -103,19 +103,18 @@ class VrfTail:
103
103
  self.AWBGainB = meta[5]
104
104
  self.AWBGainG = meta[6]
105
105
  self.AWBGainR = meta[7]
106
- self.AWBGainWriteB = self.AWBGainB
107
- self.AWBGainWriteGb = self.AWBGainG
108
- self.AWBGainWriteGr = self.AWBGainG
109
- self.AWBGainWriteR = self.AWBGainR
106
+ self.AWBGainWriteB = meta[8]
107
+ self.AWBGainWriteGb = meta[9]
108
+ self.AWBGainWriteGr = meta[10]
109
+ self.AWBGainWriteR = meta[11]
110
110
  self.BLC10b = np.bitwise_and(meta[12], 255)
111
111
  self.BayerOrder = np.right_shift(meta[12], 8)
112
112
  self.BLC12b = meta[13]
113
113
  self.Reserve[1::2] = np.right_shift(meta[14:53], 8)
114
114
  self.Reserve[::2] = np.bitwise_and(meta[14:53], 255)
115
+ # meta[53..56]为同一对Golden/Module值的冗余存储(见GetMeta), 读前两个槽位即可
115
116
  self.WBGoldenRG = meta[53]
116
117
  self.WBModuleBG = meta[54]
117
- self.WBGoldenRG = meta[55]
118
- self.WBModuleBG = meta[56]
119
118
  self.DrcGainDark = np.bitwise_and(meta[57], 255)
120
119
  self.DrcGain = np.right_shift(meta[57], 8)
121
120
  self.ExpoTime_us = np.uint32(meta[58] + np.left_shift(meta[59], 16))
@@ -165,8 +164,8 @@ class Vrf(VrfTail):
165
164
  elif self.BitDepth == 16:
166
165
  self.packPixelNum = 8
167
166
  else:
168
- print("VRF BitDepth wrong, please check it")
169
- sys.exit()
167
+ print(f"packed VRF BitDepth {self.BitDepth} not supported, only support 8/10/12/16")
168
+ sys.exit(1)
170
169
 
171
170
  self.rowSize = int(self.Width / self.packPixelNum) # in 128bit
172
171
  if self.rowSize * self.packPixelNum < self.Width:
@@ -221,8 +220,7 @@ class Vrf(VrfTail):
221
220
  return pixels.astype(np.uint16)
222
221
  else:
223
222
  print("unpackVrf: currently only support 10bit packed image")
224
- sys.exit()
225
- return np.array([], dtype=np.uint16) # 为类型检查器添加返回
223
+ sys.exit(1)
226
224
 
227
225
  def _unpackVrf(self, src: bytes) -> np.ndarray:
228
226
  if self.Packed == 1:
@@ -233,8 +231,7 @@ class Vrf(VrfTail):
233
231
 
234
232
  def rot(self, mode: str) -> None:
235
233
  if self.Packed == 1:
236
- print("can't rotate packed image")
237
- return
234
+ raise ValueError("can't rotate packed image")
238
235
 
239
236
  choices = ["mirror", "flip", "mirror_flip"]
240
237
  if mode == "mirror":
@@ -250,7 +247,7 @@ class Vrf(VrfTail):
250
247
  self.unpackImage = np.rot90(self.unpackImage, 2)
251
248
  self.BayerOrder = np.uint8(int(self.BayerOrder) ^ 3)
252
249
  else:
253
- print(f"{mode} is not a valid choice, must be one of {choices}")
250
+ raise ValueError(f"{mode} is not a valid choice, must be one of {choices}")
254
251
 
255
252
  def _checkVrf(self) -> None:
256
253
  if self.IDString[0] == "V" and self.IDString[1] == "R" and self.IDString[2] == "F":
@@ -263,13 +260,13 @@ class Vrf(VrfTail):
263
260
 
264
261
  if self.dataSize != self.fileSize - self.metaSize:
265
262
  print("VRF size wrong, please check it")
266
- sys.exit()
263
+ sys.exit(1)
267
264
  if self.BayerOrder > 4:
268
265
  print("VRF BayerOrder wrong, please check it")
269
- sys.exit()
266
+ sys.exit(1)
270
267
  else:
271
268
  print(f"VRF tag wrong, please check it {self.IDString}")
272
- sys.exit()
269
+ sys.exit(1)
273
270
 
274
271
  def SaveVrf(self, fname: str) -> None:
275
272
  data = np.ravel(self.unpackImage)
@@ -88,10 +88,10 @@ class CamDvt(asrCamOp):
88
88
  return outPath
89
89
  else:
90
90
  loge(f"{self.tuning_assistant} 127.0.0.1 t 3000 3000 3000 gv ,error ,please check it !")
91
- sys.exit()
91
+ sys.exit(1)
92
92
 
93
- def __blcSetZero(self, maunalEnable: bool):
94
- self.writeIsp("CDigitalGainFirmwareFilter", "m_bManualMode", 0, 0, maunalEnable)
93
+ def __blcSetZero(self, manualEnable: bool):
94
+ self.writeIsp("CDigitalGainFirmwareFilter", "m_bManualMode", 0, 0, manualEnable)
95
95
  for i in range(4):
96
96
  self.writeIsp("CDigitalGainFirmwareFilter", "m_pGlobalBlackValueManual", 0, i, 0)
97
97
 
@@ -114,7 +114,7 @@ class CamDvt(asrCamOp):
114
114
  self.writeIsp("CRawDenoiseFirmwareFilter", "m_bEnable", 0, 0, rawDenoiseEnable)
115
115
 
116
116
  # debug API
117
- def manulaGainTest(self):
117
+ def manualGainTest(self):
118
118
  step = 8
119
119
  gainMin = 1500
120
120
  gainMax = 1700
@@ -168,12 +168,12 @@ class CamDvt(asrCamOp):
168
168
  self.writeIsp("CAECFilter", "m_pTotalGainManual", 0, 0, gain)
169
169
  time.sleep(0.6)
170
170
  if self.aeChl == 3:
171
- r = self.readIsp("CAECFilter", "m_pLumaRLong", 5, 7, True)
172
- g = self.readIsp("CAECFilter", "m_pLumaGLong", 5, 7, True)
173
- b = self.readIsp("CAECFilter", "m_pLumaBLong", 5, 7, True)
171
+ r = self.readIsp("CAECFilter", "m_pLumaRLong", 5, 7, True, strict=True)
172
+ g = self.readIsp("CAECFilter", "m_pLumaGLong", 5, 7, True, strict=True)
173
+ b = self.readIsp("CAECFilter", "m_pLumaBLong", 5, 7, True, strict=True)
174
174
  return [r, g, b]
175
175
  elif self.aeChl == 1:
176
- y = self.readIsp("CAECFilter", "m_pLumaMatrixLong", 5, 7, True)
176
+ y = self.readIsp("CAECFilter", "m_pLumaMatrixLong", 5, 7, True, strict=True)
177
177
  return [y]
178
178
  else:
179
179
  return [0.0, 0.0, 0.0]
@@ -182,12 +182,12 @@ class CamDvt(asrCamOp):
182
182
  self.writeIsp("CAECFilter", "m_pExpTimeManual", 0, 0, exp)
183
183
  time.sleep(0.6)
184
184
  if self.aeChl == 3:
185
- r = self.readIsp("CAECFilter", "m_pLumaRLong", 5, 7, True)
186
- g = self.readIsp("CAECFilter", "m_pLumaGLong", 5, 7, True)
187
- b = self.readIsp("CAECFilter", "m_pLumaBLong", 5, 7, True)
185
+ r = self.readIsp("CAECFilter", "m_pLumaRLong", 5, 7, True, strict=True)
186
+ g = self.readIsp("CAECFilter", "m_pLumaGLong", 5, 7, True, strict=True)
187
+ b = self.readIsp("CAECFilter", "m_pLumaBLong", 5, 7, True, strict=True)
188
188
  return [r, g, b]
189
189
  elif self.aeChl == 1:
190
- y = self.readIsp("CAECFilter", "m_pLumaMatrixLong", 5, 7, True)
190
+ y = self.readIsp("CAECFilter", "m_pLumaMatrixLong", 5, 7, True, strict=True)
191
191
  return [y]
192
192
  else:
193
193
  return [0.0, 0.0, 0.0]
@@ -237,6 +237,11 @@ class CamDvt(asrCamOp):
237
237
  Gb = raw[0::2, 1::2]
238
238
  Gr = raw[1::2, 0::2]
239
239
  R = raw[1::2, 1::2]
240
+ elif vrfObj.BayerOrder == 4:
241
+ # MONO: 无CFA, 四通道直接取全图数据, 避免返回全零均值
242
+ R = Gr = Gb = B = raw
243
+ else:
244
+ raise ValueError(f"unsupport BayerOrder: {vrfObj.BayerOrder}")
240
245
 
241
246
  if fullImg:
242
247
  meanR = np.mean(R)
@@ -329,9 +334,6 @@ class CamDvt(asrCamOp):
329
334
  return int(min)
330
335
 
331
336
  lumaThr = 220.0 # G channel 过早饱和,导致统计亮度不线性,将门限设低
332
- if lumaMin is None or lumaMid is None or lumaMax is None:
333
- exit(f"{flag} manual search error")
334
-
335
337
  if lumaMin >= lumaThr:
336
338
  return int(min)
337
339
  elif lumaMax >= lumaThr:
@@ -375,22 +377,22 @@ class CamDvt(asrCamOp):
375
377
 
376
378
  # gainMin = self.readIsp("CAECFilter", "m_pMinTotalGain")
377
379
  # gainMax = self.readIsp("CAECFilter", "m_pMaxTotalGain")
378
- gainMin = int(self.readIsp("CAECFilter", "m_pMinAnaGain"))
379
- gainMax = int(self.readIsp("CAECFilter", "m_pMaxAnaGain"))
380
- expMin = int(self.readIsp("CAECFilter", "m_pMinExpTime"))
381
- expMax = int(self.readIsp("CAECFilter", "m_pMaxExpTime"))
380
+ gainMin = int(self.readIsp("CAECFilter", "m_pMinAnaGain", strict=True))
381
+ gainMax = int(self.readIsp("CAECFilter", "m_pMaxAnaGain", strict=True))
382
+ expMin = int(self.readIsp("CAECFilter", "m_pMinExpTime", strict=True))
383
+ expMax = int(self.readIsp("CAECFilter", "m_pMaxExpTime", strict=True))
382
384
  # 动态设置曝光,使得最大增益时,统计亮度尽量不饱和
383
385
 
384
386
  if blcTest:
385
387
  logFile = self.fileGainBlc
386
388
  ExpTimeManual = expMin
387
- # ponit = self.pointBLC
389
+ # point = self.pointBLC
388
390
  else:
389
391
  logFile = self.fileGainLuma
390
392
  ExpTimeManual = self.__getExpTimeManual(gainMin, gainMax, expMin, expMax)
391
- # ponit = self.pointAE
393
+ # point = self.pointAE
392
394
 
393
- # step = (gainMax - gainMin) // ponit
395
+ # step = (gainMax - gainMin) // point
394
396
  step = 256
395
397
  print("gainMin(Q8)=", gainMin, "gainMax(Q8)=", gainMax, "step=", step)
396
398
  print("set ExpTimeManual = ", ExpTimeManual)
@@ -399,9 +401,9 @@ class CamDvt(asrCamOp):
399
401
 
400
402
  cur = 1
401
403
  total = int(math.log2(math.ceil(gainMax / gainMin))) + 1
402
- with open(os.path.join(self.outPath, logFile), "a") as f:
404
+ with open(os.path.join(self.outPath, logFile), "w") as f:
403
405
  for i in range(0, total):
404
- gain = int(gainMin * math.pow(2, i))
406
+ gain = min(int(gainMin * math.pow(2, i)), gainMax)
405
407
  meanR, meanGr, meanGb, meanB = self.__getGainLumaWithVrf(gain, ExpTimeManual)
406
408
  writeStr = f"m_pExpTimeManual(us) = {ExpTimeManual} m_pTotalGainManual(Q8) = {gain} meanRGGB(12bit) = {meanR} {meanGr} {meanGb} {meanB} {cur}/{total}\n"
407
409
  cur += 1
@@ -418,21 +420,21 @@ class CamDvt(asrCamOp):
418
420
 
419
421
  # gainMin = self.readIsp("CAECFilter", "m_pMinTotalGain")
420
422
  # gainMax = self.readIsp("CAECFilter", "m_pMaxTotalGain")
421
- gainMin = int(self.readIsp("CAECFilter", "m_pMinAnaGain"))
422
- gainMax = int(self.readIsp("CAECFilter", "m_pMaxAnaGain"))
423
- expMin = int(self.readIsp("CAECFilter", "m_pMinExpTime"))
424
- expMax = int(self.readIsp("CAECFilter", "m_pMaxExpTime"))
423
+ gainMin = int(self.readIsp("CAECFilter", "m_pMinAnaGain", strict=True))
424
+ gainMax = int(self.readIsp("CAECFilter", "m_pMaxAnaGain", strict=True))
425
+ expMin = int(self.readIsp("CAECFilter", "m_pMinExpTime", strict=True))
426
+ expMax = int(self.readIsp("CAECFilter", "m_pMaxExpTime", strict=True))
425
427
 
426
428
  if blcTest:
427
429
  logFile = self.fileExpBlc
428
430
  gainManual = gainMin
429
- ponit = self.pointBLC
431
+ point = self.pointBLC
430
432
  else:
431
433
  logFile = self.fileExpLuma
432
434
  gainManual = self.__getGainManual(gainMin, gainMax, expMin, expMax)
433
- ponit = self.pointAE
435
+ point = self.pointAE
434
436
 
435
- step = (expMax - expMin) // ponit
437
+ step = (expMax - expMin) // point
436
438
  print("expMin(us)=", expMin, "expMax(us)=", expMax, "step=", step)
437
439
  print("set gainManual = ", gainManual)
438
440
  self.writeIsp("CAECFilter", "m_pTotalGainManual", 0, 0, gainManual)
@@ -441,7 +443,7 @@ class CamDvt(asrCamOp):
441
443
 
442
444
  cur = 1
443
445
  total = (expMax - expMin) // step + 1
444
- with open(os.path.join(self.outPath, logFile), "a") as f:
446
+ with open(os.path.join(self.outPath, logFile), "w") as f:
445
447
  for i in range(expMin, expMax + 1, step):
446
448
  meanR, meanGr, meanGb, meanB = self.__getExpLumaWithVrf(gainManual, i)
447
449
  writeStr = f"m_pExpTimeManual(us) = {i} m_pTotalGainManual(Q8) = {gainManual} meanRGGB(12bit) = {meanR} {meanGr} {meanGb} {meanB} {cur}/{total}\n"
@@ -456,12 +458,12 @@ class CamDvt(asrCamOp):
456
458
  遍历totalGain与AEM统计亮度,统计经过BLC,linearization
457
459
  """
458
460
 
459
- gainMin = int(self.readIsp("CAECFilter", "m_pMinTotalGain"))
460
- gainMax = int(self.readIsp("CAECFilter", "m_pMaxTotalGain"))
461
+ gainMin = int(self.readIsp("CAECFilter", "m_pMinTotalGain", strict=True))
462
+ gainMax = int(self.readIsp("CAECFilter", "m_pMaxTotalGain", strict=True))
461
463
  # gainMin = self.readIsp("CAECFilter", "m_pMinAnaGain")
462
464
  # gainMax = self.readIsp("CAECFilter", "m_pMaxAnaGain")
463
- expMin = self.readIsp("CAECFilter", "m_pMinExpTime")
464
- expMax = self.readIsp("CAECFilter", "m_pMaxExpTime")
465
+ expMin = self.readIsp("CAECFilter", "m_pMinExpTime", strict=True)
466
+ expMax = self.readIsp("CAECFilter", "m_pMaxExpTime", strict=True)
465
467
  # 动态设置曝光,使得最大增益时,统计亮度尽量不饱和
466
468
  ExpTimeManual = self.__getExpTimeManual(gainMin, gainMax, expMin, expMax)
467
469
 
@@ -476,7 +478,7 @@ class CamDvt(asrCamOp):
476
478
  cur = 1
477
479
  total = (gainMax - gainMin) // step + 1
478
480
  writeStr = ""
479
- with open(os.path.join(self.outPath, logFile), "a") as f:
481
+ with open(os.path.join(self.outPath, logFile), "w") as f:
480
482
  for i in range(gainMin, gainMax + 1, step):
481
483
  if self.aeChl == 3:
482
484
  lumaR, lumaG, lumaB = self.__getLumaWithGain(i)
@@ -490,7 +492,7 @@ class CamDvt(asrCamOp):
490
492
  total,
491
493
  )
492
494
  elif self.aeChl == 1:
493
- luma = self.__getLumaWithGain(i)
495
+ luma = self.__getLumaWithGain(i)[0]
494
496
  writeStr = "m_pExpTimeManual(us) = %d m_pTotalGainManual(Q8) = %d luma(8bit) = %f %d/%d\n" % (
495
497
  ExpTimeManual,
496
498
  i,
@@ -509,12 +511,12 @@ class CamDvt(asrCamOp):
509
511
  遍历ExpTime与AEM统计亮度,统计经过BLC,linearization
510
512
  """
511
513
 
512
- gainMin = int(self.readIsp("CAECFilter", "m_pMinTotalGain"))
513
- gainMax = int(self.readIsp("CAECFilter", "m_pMaxTotalGain"))
514
+ gainMin = int(self.readIsp("CAECFilter", "m_pMinTotalGain", strict=True))
515
+ gainMax = int(self.readIsp("CAECFilter", "m_pMaxTotalGain", strict=True))
514
516
  # gainMin = self.readIsp("CAECFilter", "m_pMinAnaGain")
515
517
  # gainMax = self.readIsp("CAECFilter", "m_pMaxAnaGain")
516
- expMin = int(self.readIsp("CAECFilter", "m_pMinExpTime"))
517
- expMax = int(self.readIsp("CAECFilter", "m_pMaxExpTime"))
518
+ expMin = int(self.readIsp("CAECFilter", "m_pMinExpTime", strict=True))
519
+ expMax = int(self.readIsp("CAECFilter", "m_pMaxExpTime", strict=True))
518
520
  # 动态设置曝光,使得最大增益时,统计亮度尽量不饱和
519
521
  gainManual = self.__getGainManual(gainMin, gainMax, expMin, expMax)
520
522
 
@@ -528,7 +530,7 @@ class CamDvt(asrCamOp):
528
530
  cur = 1
529
531
  total = (expMax - expMin) // step + 1
530
532
  writeStr = ""
531
- with open(os.path.join(self.outPath, logFile), "a") as f:
533
+ with open(os.path.join(self.outPath, logFile), "w") as f:
532
534
  for i in range(expMin, expMax + 1, step):
533
535
  if self.aeChl == 3:
534
536
  lumaR, lumaG, lumaB = self.__getLumaWithExp(i)
@@ -543,7 +545,7 @@ class CamDvt(asrCamOp):
543
545
  )
544
546
 
545
547
  elif self.aeChl == 1:
546
- luma = self.__getLumaWithExp(i)
548
+ luma = self.__getLumaWithExp(i)[0]
547
549
  writeStr = "m_pExpTimeManual(us) = %d m_pTotalGainManual(Q8) = %d luma(8bit) = %f %d/%d\n" % (
548
550
  i,
549
551
  gainManual,
@@ -593,14 +595,20 @@ class CamDvt(asrCamOp):
593
595
 
594
596
  x = []
595
597
  y = []
598
+ skipped = 0
596
599
  with open(os.path.join(out_path, txt_file), "r") as fp:
597
- line = fp.readline()
598
-
599
- while line:
600
- # print(line.strip().split(' '))
601
- x.append(float(line.strip().split(" ")[col_x])) # get column col_x as x
602
- y.append(float(line.strip().split(" ")[col_y])) # get column col_y as y
603
- line = fp.readline()
600
+ for line in fp:
601
+ parts = line.split()
602
+ # 跳过空行/列数不足的脏行, 避免IndexError
603
+ if len(parts) <= col_x or len(parts) <= col_y:
604
+ skipped += 1
605
+ continue
606
+ x.append(float(parts[col_x])) # get column col_x as x
607
+ y.append(float(parts[col_y])) # get column col_y as y
608
+ if skipped:
609
+ loge(f"{txt_file}: skipped {skipped} malformed line(s)")
610
+ if not x:
611
+ raise ValueError(f"{txt_file}: no valid data to plot")
604
612
 
605
613
  # if not is_increasing(x) or not is_increasing(y):
606
614
  # loge("%s not increasing, please check the %s " % (ylabel, title))
@@ -621,14 +629,15 @@ class CamDvt(asrCamOp):
621
629
  # 设置x从0开始
622
630
  a1.set_xlim(0, max(x))
623
631
 
624
- # 设置坐标轴刻度
625
- ticks_x = np.linspace(0, max(x) + x[1] - x[0], 8)
632
+ # 设置坐标轴刻度(仅1个数据点时无step可用, 取0)
633
+ x_step = x[1] - x[0] if len(x) > 1 else 0
634
+ ticks_x = np.linspace(0, max(x) + x_step, 8)
626
635
  ticks_y = np.linspace(0, max(y) + 10, 8)
627
636
  a1.set_xticks(ticks_x)
628
637
  a1.set_yticks(ticks_y)
629
638
  if needSave == 1:
630
639
  plt.savefig(os.path.join(out_path, title + ".png"))
631
- plt.show()
640
+ # plt.show() # 与plot3/4Curve一致不在测试中途阻塞; reDraw*系列会自行调用plt.show()
632
641
 
633
642
  @staticmethod
634
643
  def plot3Curve(
@@ -657,16 +666,22 @@ class CamDvt(asrCamOp):
657
666
  r = []
658
667
  g = []
659
668
  b = []
669
+ skipped = 0
660
670
  with open(os.path.join(out_path, txt_file), "r") as fp:
661
- line = fp.readline()
662
-
663
- while line:
664
- # print(line.strip().split(' '))
665
- x.append(float(line.strip().split(" ")[col_x])) # get column col_x as x
666
- r.append(float(line.strip().split(" ")[col_y])) # get column col_y as r
667
- g.append(float(line.strip().split(" ")[col_y + 1]))
668
- b.append(float(line.strip().split(" ")[col_y + 2]))
669
- line = fp.readline()
671
+ for line in fp:
672
+ parts = line.split()
673
+ # 跳过空行/列数不足的脏行, 避免IndexError
674
+ if len(parts) <= col_x or len(parts) <= col_y + 2:
675
+ skipped += 1
676
+ continue
677
+ x.append(float(parts[col_x])) # get column col_x as x
678
+ r.append(float(parts[col_y])) # get column col_y as r
679
+ g.append(float(parts[col_y + 1]))
680
+ b.append(float(parts[col_y + 2]))
681
+ if skipped:
682
+ loge(f"{txt_file}: skipped {skipped} malformed line(s)")
683
+ if not x:
684
+ raise ValueError(f"{txt_file}: no valid data to plot")
670
685
 
671
686
  if not is_increasing(x) or not is_increasing(r) or not is_increasing(g) or not is_increasing(b):
672
687
  loge("%s not increasing, please check the %s " % (ylabel, title))
@@ -695,8 +710,9 @@ class CamDvt(asrCamOp):
695
710
  # 设置x从0开始
696
711
  a1.set_xlim(0, max(x))
697
712
  a1.legend()
698
- # 设置坐标轴刻度
699
- ticks_x = np.linspace(0, max(x) + x[1] - x[0], 8)
713
+ # 设置坐标轴刻度(仅1个数据点时无step可用, 取0)
714
+ x_step = x[1] - x[0] if len(x) > 1 else 0
715
+ ticks_x = np.linspace(0, max(x) + x_step, 8)
700
716
  ticks_y = np.linspace(0, max(max(r), max(g), max(b)) + 10, 8)
701
717
  a1.set_xticks(ticks_x)
702
718
  a1.set_yticks(ticks_y)
@@ -732,19 +748,23 @@ class CamDvt(asrCamOp):
732
748
  gr = []
733
749
  gb = []
734
750
  b = []
751
+ skipped = 0
735
752
  with open(os.path.join(out_path, txt_file), "r") as fp:
736
- line = fp.readline()
737
-
738
- while line:
739
- # print(line.strip().split(' '))
740
- # rc = re.compile(r"(m_pExpTimeManual.*?|m_pTotalGainManual.*?|meanRGGB.*?) = (\d+|\d+\.\d+)")
741
- # print(rc.findall(line))
742
- x.append(float(line.strip().split()[col_x])) # get column col_x as x
743
- r.append(float(line.strip().split()[col_y])) # get column col_y as r
744
- gr.append(float(line.strip().split()[col_y + 1]))
745
- gb.append(float(line.strip().split()[col_y + 2]))
746
- b.append(float(line.strip().split()[col_y + 3]))
747
- line = fp.readline()
753
+ for line in fp:
754
+ parts = line.split()
755
+ # 跳过空行/列数不足的脏行, 避免IndexError
756
+ if len(parts) <= col_x or len(parts) <= col_y + 3:
757
+ skipped += 1
758
+ continue
759
+ x.append(float(parts[col_x])) # get column col_x as x
760
+ r.append(float(parts[col_y])) # get column col_y as r
761
+ gr.append(float(parts[col_y + 1]))
762
+ gb.append(float(parts[col_y + 2]))
763
+ b.append(float(parts[col_y + 3]))
764
+ if skipped:
765
+ loge(f"{txt_file}: skipped {skipped} malformed line(s)")
766
+ if not x:
767
+ raise ValueError(f"{txt_file}: no valid data to plot")
748
768
 
749
769
  if fig == None:
750
770
  fig = plt.figure(figsize=(16, 9))
@@ -765,8 +785,9 @@ class CamDvt(asrCamOp):
765
785
  # 设置x从0开始
766
786
  a1.set_xlim(0, max(x))
767
787
  a1.legend()
768
- # 设置坐标轴刻度
769
- ticks_x = np.linspace(0, max(x) + x[1] - x[0], 8)
788
+ # 设置坐标轴刻度(仅1个数据点时无step可用, 取0)
789
+ x_step = x[1] - x[0] if len(x) > 1 else 0
790
+ ticks_x = np.linspace(0, max(x) + x_step, 8)
770
791
  ticks_y = np.linspace(0, max(max(r), max(gr), max(gb), max(b)) + 10, 8)
771
792
  a1.set_xticks(ticks_x)
772
793
  a1.set_yticks(ticks_y)
@@ -863,7 +884,7 @@ class CamDvt(asrCamOp):
863
884
  if not os.path.exists(outPath):
864
885
  os.makedirs(outPath)
865
886
  for i in range(0, int(math.log2(math.ceil(gainMax / gainMin))) + 1):
866
- gain = int(gainMin * math.pow(2, i))
887
+ gain = min(int(gainMin * math.pow(2, i)), gainMax)
867
888
  print("gain(Q8)=", gain)
868
889
  self.writeIsp("CAECFilter", "m_pTotalGainManual", 0, 0, gain)
869
890
  self.writeIsp("CAECFilter", "m_pAnaGainManual", 0, 0, gain)
@@ -890,7 +911,7 @@ class CamDvt(asrCamOp):
890
911
  if not os.path.exists(outPath):
891
912
  os.makedirs(outPath)
892
913
  for i in range(0, int(math.log2(math.ceil(gainMax / gainMin))) + 1):
893
- gain = int(gainMin * math.pow(2, i))
914
+ gain = min(int(gainMin * math.pow(2, i)), gainMax)
894
915
  print("gain(Q8)=", gain)
895
916
  self.writeIsp("CAECFilter", "m_pMinAnaGain", 0, 0, gain)
896
917
  self.writeIsp("CAECFilter", "m_pMaxAnaGain", 0, 0, gain)
@@ -921,7 +942,7 @@ class CamDvt(asrCamOp):
921
942
 
922
943
  cur = 1
923
944
  total = (endPosition - startPosition) // step + 1
924
- with open(os.path.join(self.outPath, self.fileAF), "a") as f:
945
+ with open(os.path.join(self.outPath, self.fileAF), "w") as f:
925
946
  for i in range(startPosition, endPosition + 1, step):
926
947
  self.writeIsp("CAFFilter", "m_nManualMotorPosition", 0, 0, i)
927
948
  self.writeIsp("CAFFilter", "m_bMotorManualTrigger", 0, 0, 1)
@@ -954,7 +975,7 @@ class CamDvt(asrCamOp):
954
975
  renameFile(fullpath1, newfile1)
955
976
  else:
956
977
  print("抓取vrf失败")
957
- sys.exit()
978
+ sys.exit(1)
958
979
 
959
980
  def pdafScan(self, isType2=False):
960
981
  """
@@ -223,12 +223,26 @@ class ErrCode:
223
223
  FILE_ILLEGAL = -3
224
224
 
225
225
 
226
- def fileExceptionNotFound(path: str) -> Exception:
227
- return FileNotFoundError(f"File not found: {path}")
226
+ class fileExceptionNotFound(FileNotFoundError):
227
+ """文件不存在异常。
228
228
 
229
+ 兼容旧工厂函数用法: raise fileExceptionNotFound(msg), 消息格式不变;
230
+ 同时修复旧版 except fileExceptionNotFound 触发 TypeError 的问题(工厂函数不能用于except子句)。
231
+ """
229
232
 
230
- def fileExceptionillegal(path: str) -> Exception:
231
- return ValueError(f"Illegal file: {path}")
233
+ def __init__(self, msg: str):
234
+ super().__init__(f"File not found: {msg}")
235
+
236
+
237
+ class fileExceptionillegal(ValueError):
238
+ """非法文件异常。
239
+
240
+ 兼容旧工厂函数用法: raise fileExceptionillegal(msg), 消息格式不变;
241
+ 同时修复旧版 except fileExceptionillegal 触发 TypeError 的问题(工厂函数不能用于except子句)。
242
+ """
243
+
244
+ def __init__(self, msg: str):
245
+ super().__init__(f"Illegal file: {msg}")
232
246
 
233
247
 
234
248
  def normalize_args(args: List[str]) -> List[str]:
@@ -46,6 +46,10 @@ from .tao_common import (
46
46
  from .tao_device import DevOp
47
47
 
48
48
 
49
+ class IspReadError(Exception):
50
+ """readIsp 通信失败或返回非数值时抛出(strict 模式), 避免设备断连时静默产生错误测试数据"""
51
+
52
+
49
53
  class asrTuningFile:
50
54
  def __init__(self, inFile, outFile=None):
51
55
  if not fileExist(inFile):
@@ -69,7 +73,8 @@ class asrTuningFile:
69
73
 
70
74
  def checkASRFile(self):
71
75
  try:
72
- with open(self.inFile, "rt", encoding="utf-8", errors="replace") as f:
76
+ # 不用errors="replace": 非UTF-8文件需触发UnicodeDecodeError, 由下方except给出转码提示
77
+ with open(self.inFile, "rt", encoding="utf-8") as f:
73
78
  content = f.read()
74
79
  if "//ASR" in content:
75
80
  return self.asrHeaderType
@@ -84,7 +89,8 @@ class asrTuningFile:
84
89
  return 0
85
90
 
86
91
  def readFile(self):
87
- with open(self.inFile, "r") as fileObj:
92
+ # 与checkASRFile统一UTF-8编码, 避免中文Windows默认GBK读UTF-8文件产生乱码; utf-8-sig兼容带BOM的文件
93
+ with open(self.inFile, "r", encoding="utf-8-sig") as fileObj:
88
94
  if self.fileType == self.asrTuningType:
89
95
  self.tuningFileLines = fileObj.readlines()
90
96
  elif self.fileType == self.asrHeaderType:
@@ -690,11 +696,12 @@ class asrCamOp(DevOp):
690
696
  self.tuningGetModuleGroup()
691
697
 
692
698
  def readIsp(
693
- self, CFliter: str, param: str, row=0, col=0, is_float=False, showCmd=False, module=0, group=0
699
+ self, CFilter: str, param: str, row=0, col=0, is_float=False, showCmd=False, module=0, group=0, strict=False
694
700
  ) -> Union[int, float]:
701
+ """读取ISP参数; strict=True时通信失败或返回非数值抛出IspReadError, 而非静默返回0"""
695
702
  if sysVersion == "linux":
696
703
  eExit("tuning_assistant not support linux")
697
- cmd = f"{self.tuning_assistant} 127.0.0.1 t 3000 3000 3000 r m{module}_g{group} {CFliter} {param} {row} {col}"
704
+ cmd = f"{self.tuning_assistant} 127.0.0.1 t 3000 3000 3000 r m{module}_g{group} {CFilter} {param} {row} {col}"
698
705
  try:
699
706
  out = rCmd(cmd, sleep_s=0.5, showCmd=showCmd, logLevel="info")[0].strip()
700
707
  if row > 0 or col > 0:
@@ -709,21 +716,24 @@ class asrCamOp(DevOp):
709
716
  result = ctypes.cast(ctypes.pointer(tmp), ctypes.POINTER(ctypes.c_float)).contents.value
710
717
  return float(result)
711
718
  return int(cmdResult)
712
- logCallErr(f"{cmd}, please check the command.")
713
- return 0
714
- # self.tcpRemove()
715
- # raise Exception("cmd fail")
716
719
  except Exception as e:
717
- logCallErr(e)
720
+ logCallErr(f"readIsp failed, cmd: {cmd}, err: {e}")
721
+ if strict:
722
+ raise IspReadError(f"readIsp failed, cmd: {cmd}") from e
718
723
  return 0
719
724
 
720
- def writeIsp(self, CFliter: str, param: str, row: int, col: int, value: Union[int, float], showCmd=False):
725
+ logCallErr(f"readIsp get non-numeric result, cmd: {cmd}, out: {out}")
726
+ if strict:
727
+ raise IspReadError(f"readIsp non-numeric result, cmd: {cmd}")
728
+ return 0
729
+
730
+ def writeIsp(self, CFilter: str, param: str, row: int, col: int, value: Union[int, float], showCmd=False):
721
731
  if sysVersion == "linux":
722
732
  eExit("tuning_assistant not support linux")
723
733
  if isinstance(value, float):
724
734
  cf = ctypes.c_float(value)
725
735
  value = ctypes.cast(ctypes.pointer(cf), ctypes.POINTER(ctypes.c_int)).contents.value
726
- cmd = f"{self.tuning_assistant} 127.0.0.1 t 3000 3000 3000 w m0_g0 {CFliter} {param} {row} {col} {value}"
736
+ cmd = f"{self.tuning_assistant} 127.0.0.1 t 3000 3000 3000 w m0_g0 {CFilter} {param} {row} {col} {value}"
727
737
  out, _error = rCmd(cmd, sleep_s=0.5, showCmd=showCmd, logLevel="info")
728
738
  checkMsg(out, "error")
729
739
  logd(f"{out} {_error}")
@@ -19,6 +19,7 @@ from .tao_common import (
19
19
  loge,
20
20
  logi,
21
21
  logd,
22
+ logw,
22
23
  normalize_args,
23
24
  register_command,
24
25
  )
@@ -34,25 +35,17 @@ def get_file_index(filename):
34
35
 
35
36
 
36
37
  def get_meta_file_by_index(path, file_index):
37
- file_list = os.listdir(path)
38
- meta_fname = ""
39
- for f in file_list:
38
+ for f in os.listdir(path):
40
39
  if f.endswith("_%d.txt" % (file_index)):
41
- meta_fname = f
42
- break
43
- meta_fname = path + "\\" + meta_fname
44
- return meta_fname
40
+ return os.path.join(path, f)
41
+ raise FileNotFoundError(f"meta file *_{file_index}.txt not found in {path}")
45
42
 
46
43
 
47
44
  def get_meta_file(path):
48
- file_list = os.listdir(path)
49
- meta_fname = ""
50
- for f in file_list:
45
+ for f in os.listdir(path):
51
46
  if f.endswith(".xml"):
52
- meta_fname = f
53
- break
54
- meta_fname = path + "\\" + meta_fname
55
- return meta_fname
47
+ return os.path.join(path, f)
48
+ raise FileNotFoundError(f"meta file *.xml not found in {path}")
56
49
 
57
50
 
58
51
  def grep_info(tag, meta_txt):
@@ -64,6 +57,11 @@ def grep_info(tag, meta_txt):
64
57
  def unpack_mipi_raw10(byte_buf):
65
58
  data = np.frombuffer(byte_buf, dtype=np.uint8)
66
59
  # 5 bytes contain 4 10-bit pixels (5x8 == 4x10)
60
+ # 尾部不足一组(5字节)的数据解不出像素, 截断避免reshape报错(如width*5//4向下取整产生的余数)
61
+ usable = data.shape[0] // 5 * 5
62
+ if usable != data.shape[0]:
63
+ logw(f"unpack_mipi_raw10: 截断尾部 {data.shape[0] - usable} 字节(不是5的倍数)")
64
+ data = data[:usable]
67
65
  b1, b2, b3, b4, b5 = np.reshape(data, (data.shape[0] // 5, 5)).astype(np.uint16).T
68
66
  p1 = (b1 << 2) + ((b5) & 0x3)
69
67
  p2 = (b2 << 2) + ((b5 >> 2) & 0x3)
@@ -76,6 +74,11 @@ def unpack_mipi_raw10(byte_buf):
76
74
  def unpack_mipi_raw12(byte_buf):
77
75
  data = np.frombuffer(byte_buf, dtype=np.uint8)
78
76
  # 3 bytes contain 2 12-bit pixels (3x8 == 2x12)
77
+ # 尾部不足一组(3字节)的数据解不出像素, 截断避免reshape报错
78
+ usable = data.shape[0] // 3 * 3
79
+ if usable != data.shape[0]:
80
+ logw(f"unpack_mipi_raw12: 截断尾部 {data.shape[0] - usable} 字节(不是3的倍数)")
81
+ data = data[:usable]
79
82
  b1, b2, b3 = np.reshape(data, (data.shape[0] // 3, 3)).astype(np.uint16).T
80
83
  p1 = (b1 << 4) + ((b3) & 0xF)
81
84
  p2 = (b2 << 4) + ((b3 >> 4) & 0xF)
@@ -86,6 +89,11 @@ def unpack_mipi_raw12(byte_buf):
86
89
  def unpack_mipi_raw14(byte_buf):
87
90
  data = np.frombuffer(byte_buf, dtype=np.uint8)
88
91
  # 7 bytes contain 4 14-bit pixels (7x8 == 4x14)
92
+ # 尾部不足一组(7字节)的数据解不出像素, 截断避免reshape报错
93
+ usable = data.shape[0] // 7 * 7
94
+ if usable != data.shape[0]:
95
+ logw(f"unpack_mipi_raw14: 截断尾部 {data.shape[0] - usable} 字节(不是7的倍数)")
96
+ data = data[:usable]
89
97
  b1, b2, b3, b4, b5, b6, b7 = np.reshape(data, (data.shape[0] // 7, 7)).astype(np.uint16).T
90
98
  p1 = (b1 << 6) + (b5 & 0x3F)
91
99
  p2 = (b2 << 6) + (b5 >> 6) + (b6 & 0xF)
@@ -95,66 +103,58 @@ def unpack_mipi_raw14(byte_buf):
95
103
  return unpacked
96
104
 
97
105
 
98
- def convertMipi2RawWithStrde(mipiFile, bitDeepth, width, height, stride):
106
+ def convertMipi2RawWithStride(mipiFile, bitDepth, width, height, stride):
99
107
  mipiData = np.fromfile(mipiFile, dtype="uint8")
100
108
 
101
109
  # print(mipiFile," file size:", mipiData.size)
102
110
  mipiData.resize(height, stride)
103
111
  # print(mipiData.shape)
104
112
 
105
- if bitDeepth == 8 or bitDeepth == 16:
113
+ if bitDepth == 8 or bitDepth == 16:
106
114
  print("raw8 and raw16 no need to unpack")
107
115
  return None
108
- elif bitDeepth == 10:
116
+ elif bitDepth == 10:
109
117
  byte2pixel = 5 / 4 # 5 bytes contain 4 10-bit pixels (5x8 == 4x10)
110
118
  dataWithoutStride = np.ascontiguousarray(mipiData[::, : int(width * byte2pixel) :])
111
119
  bayerData = unpack_mipi_raw10(dataWithoutStride)
112
- elif bitDeepth == 12:
120
+ elif bitDepth == 12:
113
121
  byte2pixel = 3 / 2 # 3 bytes contain 2 12-bit pixels (3x8 == 2x12)
114
122
  dataWithoutStride = np.ascontiguousarray(mipiData[::, : int(width * byte2pixel) :])
115
123
  bayerData = unpack_mipi_raw12(dataWithoutStride)
116
- elif bitDeepth == 14:
124
+ elif bitDepth == 14:
117
125
  byte2pixel = 7 / 4 # 7 bytes contain 4 14-bit pixels (7x8 == 4x14)
118
126
  dataWithoutStride = np.ascontiguousarray(mipiData[::, : int(width * byte2pixel) :])
119
127
  bayerData = unpack_mipi_raw14(dataWithoutStride)
120
128
  else:
121
- print("unsupport bayer bitDeepth:", bitDeepth)
129
+ print("unsupport bayer bitDepth:", bitDepth)
122
130
  return
123
131
 
124
132
  # bayerData.tofile("tmp1920x1080_raw12.raw")
125
133
  return bayerData
126
134
 
127
135
 
128
- def convertMipi2Raw(mipiFile, bitDeepth, imgWidth, imgHeight, bayer_order=cv2.COLOR_BayerBG2BGR):
136
+ def convertMipi2Raw(mipiFile, bitDepth, imgWidth, imgHeight, bayer_order=cv2.COLOR_BayerBG2BGR):
129
137
  mipiData = np.fromfile(mipiFile, dtype="uint8")
130
138
  print("mipiraw file size:", mipiData.size)
131
139
  bayerData = None
132
140
 
133
- if bitDeepth == 8 or bitDeepth == 16:
141
+ if bitDepth == 8 or bitDepth == 16:
134
142
  print("raw8 and raw16 no need to unpack")
135
143
  return None
136
- elif bitDeepth == 10:
144
+ elif bitDepth == 10:
137
145
  # raw10
138
146
  bayerData = unpack_mipi_raw10(mipiData[: imgWidth * imgHeight * 5 // 4])
139
- img = bayerData >> 2
140
- elif bitDeepth == 12:
147
+ elif bitDepth == 12:
141
148
  # raw12
142
149
  bayerData = unpack_mipi_raw12(mipiData[: imgWidth * imgHeight * 3 // 2])
143
- img = bayerData >> 4
144
- elif bitDeepth == 14:
150
+ elif bitDepth == 14:
145
151
  # raw14
146
152
  bayerData = unpack_mipi_raw14(mipiData[: imgWidth * imgHeight * 7 // 4])
147
- img = bayerData >> 6
148
153
  else:
149
- print("unsupport bayer bitDeepth:", bitDeepth)
154
+ print("unsupport bayer bitDepth:", bitDepth)
150
155
 
151
156
  # bayerData.tofile(mipiFile[:-4]+'_unpack.raw')
152
157
 
153
- # img = img.astype(np.uint8).reshape(imgHeight, imgWidth, 1)
154
- # # print(bayer_order)
155
- # rgbimg = cv2.cvtColor(img, bayer_order)
156
- # cv2.imwrite(mipiFile[:-4]+'_unpack.jpg', rgbimg)
157
-
158
158
  return bayerData
159
159
 
160
160
 
@@ -193,8 +193,11 @@ Returns:
193
193
 
194
194
 
195
195
  def raw2vrf(
196
- raw_name, width, height, BLC10b, BayerOrder, BitDepth, stride=0, isMipiRaw=False, dgain=1.0, WBGain=[1.0, 1.0, 1.0]
196
+ raw_name, width, height, BLC10b, BayerOrder, BitDepth, stride=0, isMipiRaw=False, dgain=1.0, WBGain=None
197
197
  ):
198
+ # 避免可变默认参数, None时取默认值
199
+ if WBGain is None:
200
+ WBGain = [1.0, 1.0, 1.0]
198
201
 
199
202
  path, filename = os.path.split(raw_name)
200
203
 
@@ -220,6 +223,11 @@ def raw2vrf(
220
223
  vrfObj.AWBGainB = np.uint16(128 * grep_info("gain_b", meta_txt))
221
224
  vrfObj.AWBGainG = np.uint16(128 * grep_info("gain_g", meta_txt))
222
225
  vrfObj.AWBGainR = np.uint16(128 * grep_info("gain_r", meta_txt))
226
+ # meta[8..11]为per-channel write增益, 与主增益同步, 保持与旧版文件输出一致
227
+ vrfObj.AWBGainWriteB = vrfObj.AWBGainB
228
+ vrfObj.AWBGainWriteGb = vrfObj.AWBGainG
229
+ vrfObj.AWBGainWriteGr = vrfObj.AWBGainG
230
+ vrfObj.AWBGainWriteR = vrfObj.AWBGainR
223
231
 
224
232
  vrfObj.AGain = np.uint16(16 * grep_info("shortGain", meta_txt))
225
233
  vrfObj.TGain = np.uint16(vrfObj.AGain * dgain)
@@ -231,6 +239,11 @@ def raw2vrf(
231
239
  vrfObj.AWBGainB = np.uint16(128 * WBGain[2])
232
240
  vrfObj.AWBGainG = np.uint16(128 * WBGain[1])
233
241
  vrfObj.AWBGainR = np.uint16(128 * WBGain[0])
242
+ # meta[8..11]为per-channel write增益, 与主增益同步, 保持与旧版文件输出一致
243
+ vrfObj.AWBGainWriteB = vrfObj.AWBGainB
244
+ vrfObj.AWBGainWriteGb = vrfObj.AWBGainG
245
+ vrfObj.AWBGainWriteGr = vrfObj.AWBGainG
246
+ vrfObj.AWBGainWriteR = vrfObj.AWBGainR
234
247
 
235
248
  vrfObj.AGain = np.uint16(16)
236
249
  vrfObj.TGain = np.uint16(vrfObj.AGain * dgain)
@@ -242,7 +255,7 @@ def raw2vrf(
242
255
  vrfObj.PrintVrf()
243
256
  if isMipiRaw:
244
257
  if stride != 0:
245
- bayerData = convertMipi2RawWithStrde(raw_name, vrfObj.BitDepth, width, height, stride)
258
+ bayerData = convertMipi2RawWithStride(raw_name, vrfObj.BitDepth, width, height, stride)
246
259
  else:
247
260
  bayerData = convertMipi2Raw(raw_name, vrfObj.BitDepth, width, height)
248
261
  else:
@@ -251,7 +264,8 @@ def raw2vrf(
251
264
  else:
252
265
  bayerData = np.fromfile(raw_name, dtype="uint16")
253
266
 
254
- if bayerData != None:
267
+ # 注意: bayerData是numpy数组时, "!= None"会做逐元素比较并抛ValueError, 必须用is not None
268
+ if bayerData is not None:
255
269
  vrfObj.unpackImage = bayerData.astype(np.uint16)
256
270
  else:
257
271
  eExit("get bayer data failed")
@@ -285,9 +299,12 @@ def raw2vrfBatch(
285
299
  stride,
286
300
  isMipiRaw=False,
287
301
  dgain=1.0,
288
- WBGain=[1.0, 1.0, 1.0],
302
+ WBGain=None,
289
303
  suffix="raw",
290
304
  ):
305
+ # 避免可变默认参数, None时取默认值
306
+ if WBGain is None:
307
+ WBGain = [1.0, 1.0, 1.0]
291
308
  file_list = os.listdir(path)
292
309
  for f in file_list:
293
310
  f_lower = f.lower()
@@ -330,6 +347,11 @@ def map_colorchecker_to_bitdepth(raw_color_values_8bit, dataMin, dataMax, out_dt
330
347
  return mapped.astype(out_dtype)
331
348
 
332
349
 
350
+ def blc10b_to_bitdepth(blc10b, bitDepth):
351
+ """把10bit黑电平换算到指定位深: 8bit=÷4, 10bit=不变, 12bit=×4, 14bit=×16, 16bit=×64"""
352
+ return int(int(blc10b) * math.pow(2, int(bitDepth) - 10))
353
+
354
+
333
355
  def get_bayer_pattern(bayer_order):
334
356
  """返回 2x2 pattern,索引方式 pattern[row_phase][col_phase] -> 'R'/'G'/'B'"""
335
357
  patterns = {
@@ -380,7 +402,7 @@ def generateVrf(outPath, width, height, bitDepth=10):
380
402
  vrfObj.BLC10b = np.uint8(0)
381
403
 
382
404
  dataMax = int(math.pow(2, bitDepth)) - 1
383
- dataMin = int(vrfObj.BLC10b * (vrfObj.BitDepth - 9))
405
+ dataMin = blc10b_to_bitdepth(vrfObj.BLC10b, vrfObj.BitDepth)
384
406
 
385
407
  logi(f"bitDepth:{bitDepth} wxh: {width,height} dataRange: {dataMin,dataMax}")
386
408
 
@@ -481,7 +503,7 @@ def generateRandomVrf(outPath, width, height, bitDepth=10):
481
503
  vrfObj.Height = np.uint16(height)
482
504
 
483
505
  dataMax = int(math.pow(2, bitDepth)) - 1
484
- dataMin = int(vrfObj.BLC10b * (vrfObj.BitDepth - 9))
506
+ dataMin = blc10b_to_bitdepth(vrfObj.BLC10b, vrfObj.BitDepth)
485
507
  # 生成10位随机噪声数据(0-1023)
486
508
  logi(f"bitDepth:{bitDepth} wxh: {width,height} dataRange: {dataMin,dataMax}")
487
509
  random_noise = np.random.randint(dataMin, dataMax, (height, width), dtype=np.uint16) # 10位数据范围是0-1023
@@ -497,6 +519,11 @@ def makeNoiseToVrf(vrfFile: str, noiseLevel: float):
497
519
  if not path.is_file():
498
520
  raise FileNotFoundError(f"{vrfFile} 不是一个有效的文件")
499
521
 
522
+ # noiseLevel<=0 时 randint(low,low) 会报 ValueError(low >= high), 且加零噪声无意义, 直接跳过
523
+ if noiseLevel <= 0:
524
+ logw(f"noiseLevel={noiseLevel} <= 0, 无噪声可添加, 跳过: {vrfFile}")
525
+ return
526
+
500
527
  outPath, _, nameWithoutSuffix, _ = path.parent, path.name, path.stem, path.suffix
501
528
 
502
529
  vrfObj = Vrf()
@@ -504,13 +531,14 @@ def makeNoiseToVrf(vrfFile: str, noiseLevel: float):
504
531
  bitDepth = vrfObj.BitDepth
505
532
 
506
533
  dataMax = int(math.pow(2, bitDepth)) - 1
507
- dataMin = vrfObj.BLC10b * (vrfObj.BitDepth - 9)
534
+ dataMin = blc10b_to_bitdepth(vrfObj.BLC10b, vrfObj.BitDepth)
508
535
 
509
536
  # 生成随机噪声, 噪声范围可以根据需要调整
510
537
  noiseMax = int(noiseLevel * dataMax)
511
538
  noiseMin = -noiseMax
512
539
  print(f"bitDepth:{bitDepth} noiseRange: {noiseMin,noiseMax}")
513
- random_noise = np.random.randint(noiseMin, noiseMax, (vrfObj.Height, vrfObj.Width), dtype=np.int16)
540
+ # dtype用int32: 16bit时noiseMax=65535超出int16范围, 用int16会直接报错
541
+ random_noise = np.random.randint(noiseMin, noiseMax, (vrfObj.Height, vrfObj.Width), dtype=np.int32)
514
542
 
515
543
  # 将噪声添加到原始数据中
516
544
  noisy_data = vrfObj.unpackImage + random_noise
@@ -584,7 +612,10 @@ def CLI_raw2vrf(argsList):
584
612
  def rotVrf(input, output, mode):
585
613
  vrfObj = Vrf()
586
614
  vrfObj.Read(input)
587
- vrfObj.rot(mode)
615
+ try:
616
+ vrfObj.rot(mode)
617
+ except ValueError as e:
618
+ eExit(f"rotVrf failed: {e}")
588
619
  vrfObj.SaveVrf(output)
589
620
 
590
621
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taotoolkit
3
- Version: 1.1.7
3
+ Version: 1.1.8
4
4
  Summary: Tao ToolKit
5
5
  Author-email: taotaoli <taotaoli@asrmicro.com>
6
6
  License-Expression: MIT
File without changes
File without changes