e6&41!I&t=ZC;u0u{9*E{mc%%Qo^tqCa
zgui}O*QV54aG%PV{mBx~5{w}j12_F2@LBytrzg=C5THZdhC>&^IX9b*-I4j8M@LC7
zYTsOA#h>isUIV`{H?Y@0B4?}Bw=16t7vMxhVEw}1wT2Jx2A#^~O%eyU@DJ1MH;^nf
ziPS@p1(R0$ra@c$gc8B9AsY0%9@BPo-En$Wpnaw_t1QWqF3pXT&8dI0<9$ssUH?@E
zQ)fHd`OEn_C^aT4Sup%sf?jSZM^mcwe?KecMy193ZFZJF2YQKp9WKDOqwF$
zv$yttEBG4(dq$Xi`@S?(w*Hw7YS=xbP*A|oUumQq5k|q&enDik{jzI(vgYCXFCdID
z7@|=qjeJvMU198dJC8U=nqDSIJ;_kE)nbf;TMM!`Vi%K>i>rB3)jrZon!*h}Rg$c{
zcNv3{^{^fPqVzZ|=wiDnf8dblQ(_7ciU)g;J^CvJ#jT(4rd_2>X2Nf;dn`RTWr2cs1Xo#}P6$7_c_
z@9nl$0pPjrYyq8L4+jW>6Q>d!N6THbNJ!ke)NL?l3e+LkyDK5!g}0FKz?U-k!Bm(?
zoC%ze=h5kg!`ly00oP4IcY_~++nvc5*grj_Q=j>-#@x}w=7TU4t-t*sVb52>
zyvL)08QGor-s|C3RhE8x*OOR<+4FaSM40L+h-5U+us5@o>D~7F?$mA*iJW%I
z=;-BC`)|%NV{=I9|A9ydJj+TKZND5F9y)q;rEbsb1I7rf8TT8LR;+UZd
z5jKmT^#zB97&sper|
z-J5HKT!7+zU-r0~(Y6CK1()4I;t#pFa?!yTPs!Jn_RDIO|HzGqYOuk6P|AnNzfPwm
z%IJw@BuFPE!m3{N9Z%NO6;O{ZE3BO1B`mr1w!i+I;W^@*UAJ*_`YJOkdOQ2^*0_g>
zHYE`7_a3SL^(!N`eltBxX}-CpcyWksqJlZ^$tKbVrbY6#A}ohtw=sY?L_{Gk1fd%=u774PvO&8=GN`$$IL(k)oir@D7^zJ%TJ3_
zA|Tn+)7!sx+nCbe`zdMFly7MIYk1(qj{BhcOkZpQmxz)!VChDumO|bgws^Y{fKl>l
z;crat((CypSBaFgm32zg3mmDQ>&3;#0*Ra|Jf9e&N$Grs3^;%F3)VKQJjwyh_T
zIwm~M9Y%|^h)`p}`>4>tLCxm|Lf8r!u7Noc=C%`CSc3|5LU6?9x0f9YY@t@Nj{WAk
zje0vq)n;dz3E7QqRuD$;($@Ai-?q5k*%_%Kd+AqhNrcmNXZw7_Bam*xe6E4+c#pox
z4E!^SCdyi9)$-*#lNTH!{@^CkgAr?YUIG$w#$*mc`NfV7GgD@ulNE}iA|V}rAKN^1
z2w;5c^^@7GtSb%fGHOw^xcF<c@AMS$@xXbjFe`Hts;!F
zhbAiR?CTcz%+dGh)QaL0R`G1>f^2~;U(tmr+2B>5EfrbD?cLrQ5c1DuMg0s3^2434
z;FdOjt9>gu$##ir3ymFL3Bw0i$&!I)db22XcOK8bohu3&OR9oc{+WFLAwhneOiuWF
zV-q!MuAu;phAdOm2Mo{=h1lI4EI1#a*^`OQ&Ke!O+S=fa@Sg2=v();$!{y
z8#^y#Cim|H
zYvl|s1BS+>*|IQuVO}2S@tDz*bQCdZuLz$wtDpon7x?kp9##;bNF>!hzTd@RPqUo23M*XMZ6L?Q
zgd_sgv3n}cNP=)Gn#-Z3dzzZ2L3DO;kK5>_c%A?~Zj0ot?S6~6dp;aan9hgHv+q6~
zah_`_v8BZ5ksHDARaP*-g}3VTZ}{we2Qp(M({aE|)$Vng?e5J)&;5g9Xm9HcVLFs~
zchtckc`S+pL1UTIV?r8_TR3wSSC{J>*p9
z*t7mYt1_jwM8jdXTtfoJOLa}+k>K#gn*lQumW_r`VADRN#)@5K4|b(p<|6{5yP$X&
r#nk-t-+W&ve4J=mSmFPfH$ec-{qz1aD+kPf2tZ9qQ?XLsEcAZ>spb0)
literal 0
HcmV?d00001
diff --git a/tests/data/drawDBSCAN.png b/tests/data/drawDBSCAN.png
deleted file mode 100644
index 3b85966f0bd260359e86efd88ba60a236462921f..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 5891
zcmY+IcOcc@|HoY`BcWtuMlLe0%XV
zW!!An=JGr0`_JzW@At)hpL1U0{dhjli8j>Nq@%e)LqbAAr>&)C4DN(9MrZhTFZjpi`eW|Y;Gd2xsj}1%^X(Hc+G|y>E(=%vBB$nCd}x)w
z{ZKN%6V}=YZS-8bxF?ogm*grx^nP?OYYKYj#m&a0wcj$--B*295%B|JuT`t9kDpyb
zY+j$`vbCGALSz%U1AqHmrRvcZ>6bit8sV4ak%g0obRETPK=`J4+kIm8*niIOTNX8_
zGDPBtYW{xI1hwc}o2}QHn&BTAC`{Gb;=yb8$AxkZ8zBTgw$Ro0h&n3F*oN(^HMok5(acZ}Xjv
zMncow&7_Dpw5x{+uY`AOzF%O~hcn_TFl5{`2CGR-+X1Q=vt3d3x%)>^lavJO;yQ
zjrNORLeiK&hbXfni+U!r|2T|hyC=$~y`jt_GW^Hcv;dM~BVg`l|uAYRey=hgBFjvDz^?X8hpkjtvB~7Ya3{3NsrIX(zDab3=dCj!i
zeqht8m%nbhy52CYd}T?~bBemZq`ZPQDkH`HzjyDnwQm)6nI_9+zD#`QeOvJgw16Eq
zLXuMtWqsIvH=`zR+-eqNdlf2Dfoc_FeMp(?E)IK5o=o9s-kEQ=72x_T??C}O{K0)|
zBvd)`B}Dl#U1jjhcXZIMXHNY>O22?#`4o$MKu9j(dVPwA$-k0M*v(*BErDRdA^qV^hm^~X6;xSI-Es*u^$C^D|0*ls
z)RWXgZQSX?n9wZ&vdZ)I`|pa{lIzY}m(F7B7?0!DXy
zDlC=R=w3u$O92s(Y&whNo&_y5ftT}5QI@({>D1FERYLMO!iJN3c{9LOe14p!$0^GE
z$`x%!wLJd{s{W)DmumgjE!3Xo;?bI9n6mivHYy?9h?eJoV>gCZN47KnpjkQ%WCaA`
zg8phuvzX%8u27rCvN(PJb&=|_jvRM~!k9r0xL
z-w)Rm%a+3)V{J^POSlwAHwc=4{#8!E
zb_IH`?2s%+d1kABor@?_|Gcs}_D(rMHJPb^y_rn^4ef1pzNEB&y=of>W@#mSyF{;G4VQEiz^Nhh6f^9hd=D~BQQ>{_BD2*87xbi$
zmNN{bnEAanw7Y1NSxKM;0>1YsEKJGH25rK{kn0%K{CNEgNe
z_LDE>%v3(U{$r1B)-L`qFi^pQ1`ER7rQCyXGJMR$f^BK
zxrl)605q&u@7>-O``k&lY;3vSoVg*u9QIGp}0ZGLKemTUMJfu&-{_iC>HFqJM9
zso-6oU`~ef(!w*9th>c6dx$Qs%(#O41yZ4RhP4C=r>EalRjKkwgseVwQh*lqQ*>f@
z!Ruvc{v%GaJ1XDKb}TB(N#6S7(T2duAJTAo
zFzJ2rLPeDYMvTsf*ID9aAepH(&ocO0(Zz5(YP0E}q6I
z)*nTm?!9^c`%QVgfq@29P1>*p;mdr|h{w3i{i(A;>mqd0-qh4P^GfK&psSga{*7>+
zxPfmE_2Y(y23-C+F*72)IoTNRt9SBc()PoBJS7iT98*I6=ky2MIW&(6hxoX9#ZwVo
zYC(4j0PSSK38Wna#W9naqjFaJIw
zkh#TGN&$YULB1CjO^wY`JR%UXRsp?0H-ZkgGf%7;YI<;cK4YfCBwwi`Z}?lVm}CdF
zzr2c8`DMJ9X9uy_$#(YN4SimLiTG@lbg@E
z66f#1b4x~TtalzAB@Fx3k^Lp|8BOzlivIwex;7awtm8LSb*X2W{;B+o%doFQ?4QHM
zlT{*6%t)a2%#7~cuU&jrdZ!!Rxxdc(A!Qg%&U&2K3k`kNm{gJT;Ktuvoy`GT40&3f
zZv`lr-cY!Ger{yiT33l0<+3iJ`uCCWRk=M!wT{Beh2mGLO;zN+ckYKq!n+iSvC~m>v>^^rq{3HRG<2
z-_ACB(lb0QmSfZQcpe58%*;S;_yLd|Zjt0)8#|{`NvtIWBj?mpj@NgnT*}nWta*KL
z>7l3x>N~R=jrS)?P$EF!WOo3miVM~pOHE%c#vh9meVMLA;S#uyji+?mdeA4VLhsb_
z8Ym*_slZ*TzUV`7l@>@
zD=+BIOnc$d@w$>n^Th+_1w6LLjr4&2rvVeie9`bYJ|Z$A0QjIRQSOl~ny}TP(fc{`
z@wQuE!g2UDU2n^y=RW6Pt+Q2+U!4AKBq`)OqUTod*+vhq)HqecW
zCa2re30n9#v=MTSiiv;vbRV7LkR1kO2ALg(^SgFT(-v&dW;wIgIY4e0Fyi%KY`a{N
zZPl-dlWijUSi;wyKt@FxYW#=zcALuC7z4
zGM=?FImrSw@@alVoDVPJ5;nZM*^Pg(gp&eh5EnVP=wyIYvc`S$0NFm%S9`BjPu`L@AE
z>f+x9E`FNgZm7q>O|4J-vI9v$l7nY6+WK7SxdY#CMskw@&PJh$IecVfRDvO{?G_OM
zspm`9!!snC3X^I);Zd3-o;UA`nBHh+be<}{lpqjv7#n{>Pe&Gr=dnEA^o7-mMNA3k
ze`Z2}E1-^J0e_D^2Ouyc$a8oo$A0hp^z@cvzIiI
zhbB^+!SGl(?=TNlSB5&D@L@$n7pdQc47l`<#9W}
z*xw**KcrItJC*xjuEi#3OZWYLvvlb3k2fbhNufRg`#99IG9T^}wO_O^JgW#zO#hCZFmXx${VTq3@Aa9DUWTyaJK-73im?wtTvu8<#$
zFGd5m$46{GOx$?W=ryBktiOk@E!rPy@|{geizNY^z8!RdRKKXEsi^*-NTqQ+B%>ZU
zdj{rzh8MdR2(jlaZL~^zU=WEIK(&rnW2Bu-!hE2K4KkD;v=k?}`MZo)$X^qUbgM3D
z?P@~)&fQg;htymf|6)=DgC6ClA_WQ^LP7Q+@hd7%S2{g;fGY;;2E1PjiknkX!Jw4T
zG}t_)bDA1E$BOjOB5X7s02I8((>%Eis)&I)(P8T>X*XRRk@7|>P>(vO2(>F_i50NS
z_F_Vm_SAp6F)^Lm+Pj*fUHUu|+!P{R`hB(b67t=(bd8^N_F}e1mz@lH3Y|W9|;$uJG~t^_K#;0+^^4oW3QqC%r;ZM`aE8eCYyaR0I_2}n2^M~AIq#-JXmZyXPJqwVJM$#W
z4Gc7DR5cL=_j-Go(c#DfjnS)xRr6~;aT;aB|gy*chU4M-7IPU_p~t1+_hsG`d>
zN#X|Z8wUTa6HR{gnV_4czJ&|1K70U#;TQ@GB0RS&ngZNM`cVr*57$GO8UFTR39n~g
z?XSw~Qf*%!4aNM7gWISM7yramO@|97&MNrL?qGyrD2x(2uWNXX32ZL$6T3-t!Nw4M
zFxAo;UQ}2Vf(i;Gvnm6v|DK9=oRe+tFcVD?vgK_r;u_U8RGaluT>#=~zRw9H{07Bj
zh8Eb#k)|Sx944jfg&FCmo;-1a(UbI@IQI?RDQPb`vNSV`G$U(qA=+1LyIhJNEcrfr
zkeHC1lFFgrdE9%_G2;9U?@cN@4x~CBDD5TuqtT(h4Y1QGvTi@fd!=xMH!ak
z>p_&Rw^c%RC2N9eYi$rn=O{@xf^69V`lc4t@8&iq8A
zkT0oA35}CMq__+I{`W^yfWz9ml(nB#0OmQXsI%R@6qX(9xm
z-O%plBbj=xATA@3LJT<5NPd4`%P8ZjOX~a7?YSVHjdsZsdhX6|o{gNs7dQ$^WbIM=
zn1eDu_jBLirH4cG>$6RJU_o$VxWTYmk+{#^_QGPoTm8kx8Ygtn_LK;Zh^?OkQ%W+^
z(HQqc=uKhRse*x$C)lnyOUX+V6Wo_jPh6fn(Q!#dd_QlP?BTb!yX)gemMZniZ*GBh
z_$@M9J?+ii&vnm(ZtR>BbDL@9lT>JO_~f@Y+Y(6;X|N~zuc
zIFe{D5P#HPvPDqj%a>;SQYH1YjX3E45A?9qsMLI|(MycVe!R)N7JIN4ie
zNYwI25{ZKfPNrI9(gQ5ll=t$sAmxdLe+5
zlv>-*#ZX2;VNv`V
ze!k^X(E4nzw-ija$Gv7^CB7$Kc~>BZsN*0Xg`YPm(&`%~#K!(f<2s$R7lDeH2Jf{b
zj{~QkS?At_xum0~(NG2g(=U<~hK0&p8N<{r{q9V4Q_#@REOo(0H%@?&<>f|Zu>FI_
zKY~J4#%H>a?MOhqw00Is*9$Z21B21=afHmYubTN)X*Xnhka%BBJ0nJP+21g%P0cYg
z*vy7^*}V1o+e8r&kpb9sQcRhP
zOjE~dUx!p)0!k^MnXJer5Z~n#+PxLQU%b35e$Zdiumjy5`S|gpYcLU|EdSWSnSuXh
z@!@Z!3Z)sEN39iqJ{4K097V#m>cH2ELiRg6gVXByMe@OUl>iQ5WVy2Ydvk~!Wj;0@
z<8;X@I-RX#P=@^#-2}9Qg)&@fP{Qfj4M+K`W!cBo6P)e_T>Y#|%PsO#>u)OyRWXKM
z8c4I0gn7=>pGju0mNo^R<}wb0wuPf&4CMj_BgJFQqfT9~1I2R2C$_2T9WM344Tez(
zX4d`--yU7Nm~e+MXg86=3rt
z7~)47!~R5(qN~KLX?ktc_4`fE3-tmC^Asp^$(`ErA>lVR3d0o)hRt+;Pbz`Q3%j++
z450vrkp<)srWp1Jn*#r&Fq|mZ1UmXTI5b%n%x=BMu6@209bDVuwDV_cqZ9EIIy*BV
zT~1FB24}74)JhIWR~dh9gB+yGr#+L2>anp1uVs 3
-def test_kmeans_maps_work_with_drawDBSCAN(three_colors):
+def test_kmeans_maps_work_with_drawClusters(three_colors):
maps, _ = cv.kmeansColors(three_colors, 3)
- painted = cv.drawDBSCAN(three_colors, maps, maps.ravel())
+ painted = cv.drawClusters(three_colors, maps)
assert len(np.unique(painted.reshape(-1, 3), axis=0)) == 3
+def test_clusterers_return_a_named_tuple(three_colors):
+ result = cv.kmeansColors(three_colors, 3)
+ assert isinstance(result, cv.Clusters)
+ assert result.maps is result[0] and result.centers is result[1]
+ assert result.maps.dtype == np.int32 and result.centers.dtype == np.uint8
+ assert isinstance(cv.peakColors(three_colors), cv.Clusters)
+
+
+def test_drawClusters_gray_and_noise():
+ gray = np.zeros((4, 6), np.uint8)
+ gray[:, 3:] = 200
+ gray[0, 0] = 77
+ maps = np.zeros((4, 6), np.int32)
+ maps[:, 3:] = 1
+ maps[0, 0] = -1 # noise keeps its own color
+ out = cv.drawClusters(gray, maps)
+ assert out.shape == gray.shape and out.dtype == np.uint8
+ assert out[0, 0] == 77 and out[1, 0] == 0 and out[0, 5] == 200
+ np.testing.assert_array_equal(cv.drawClusters(gray, np.full((4, 6), -1)), gray)
+ with pytest.raises(ValueError, match="maps"):
+ cv.drawClusters(gray, maps[:2])
+ with pytest.raises(ValueError, match="uint8"):
+ cv.drawClusters(gray.astype(np.float32), maps)
+
+
def test_kmeans_functions_need_no_extra(monkeypatch, three_colors):
monkeypatch.setitem(sys.modules, "sklearn", None)
monkeypatch.setitem(sys.modules, "sklearn.cluster", None)
@@ -138,7 +163,7 @@ def test_meanShiftColors_finds_the_number_of_colors(noise):
assert maps.shape == img.shape[:2]
for color in (RED, GREEN, BLUE):
assert any(_close(c, color) for c in centers), color
- assert cv.drawDBSCAN(img, maps, maps.ravel()).shape == img.shape
+ assert cv.drawClusters(img, maps).shape == img.shape
def test_meanShiftColors_bandwidth_controls_merging(three_colors):
@@ -169,28 +194,34 @@ def test_clusterPoints_groups_and_noise():
pytest.importorskip("sklearn")
points = [[0, 0], [1, 0], [0, 1], [50, 50], [51, 50], [200, 0]]
labels = cv.clusterPoints(points, eps=3)
- assert labels.shape == (6,)
- assert labels[0] == labels[1] == labels[2] != 0
- assert labels[3] == labels[4] != 0
+ assert labels.shape == (6,) and labels.dtype == np.int32
+ assert labels[0] == labels[1] == labels[2] >= 0
+ assert labels[3] == labels[4] >= 0
assert labels[3] != labels[0]
- assert labels[5] == 0 # isolated point is noise
+ assert labels[5] == -1 # isolated point is noise
def test_clusterPoints_contour_input_and_minSamples():
pytest.importorskip("sklearn")
contour = np.array([[[0, 0]], [[1, 1]], [[100, 100]]], np.int32)
- assert cv.clusterPoints(contour, eps=2, minSamples=1).tolist() == [1, 1, 2]
+ assert cv.clusterPoints(contour, eps=2, minSamples=1).tolist() == [0, 0, 1]
def test_clusterPoints_validation():
with pytest.raises(ValueError):
cv.clusterPoints(np.zeros((0, 2)), eps=1)
+ with pytest.raises(ValueError, match="finite"):
+ cv.clusterPoints([[0, float("nan")]], eps=1)
+ with pytest.raises(ValueError, match="eps"):
+ cv.clusterPoints([[0, 0]], eps=0)
+ with pytest.raises(ValueError, match="minSamples"):
+ cv.clusterPoints([[0, 0]], eps=1, minSamples=0)
@pytest.mark.parametrize(
("func", "args"),
[
- ("DBSCAN", (np.zeros((2, 2, 3), np.uint8), 1.0, 2)),
+ ("dbscanColors", (np.zeros((2, 2, 3), np.uint8), 1.0, 2)),
("meanShiftColors", (np.zeros((2, 2, 3), np.uint8),)),
("clusterPoints", ([[0, 0]], 1.0)),
],
diff --git a/tests/test_common_utils.py b/tests/test_common_utils.py
index de94fa5..df1b16f 100644
--- a/tests/test_common_utils.py
+++ b/tests/test_common_utils.py
@@ -60,6 +60,7 @@ def test_clipBoxes():
def test_scaleBoxes_undoes_a_letterbox(scene):
_, scale, (left, top) = cv.letterbox(scene, (160, 160))
+ assert isinstance(cv.letterbox(scene, (160, 160)), cv.Letterbox)
box = np.array([80 - 30, 80 - 30, 60, 60], np.float64) # the first disc in the original
small = cv.scaleBoxes(box, scale, (left, top))
np.testing.assert_allclose(cv.scaleBoxes(small, scale, (left, top), inverse=True), box)
@@ -70,7 +71,7 @@ def test_scaleBoxes_undoes_a_letterbox(scene):
def test_expandBoxes():
np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], ratio=0.5), [0, 0, 40, 40])
- np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], pixels=2), [8, 8, 24, 24])
+ np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], margin=2), [8, 8, 24, 24])
np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], ratio=0.5, size=(25, 100)), [0, 0, 25, 40])
np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], ratio=-1), [20, 20, 0, 0]) # never negative
assert cv.expandBoxes(BOXES, 0.1).shape == (3, 4)
@@ -112,12 +113,12 @@ def test_findCircles_validation(scene, kwargs):
def test_detectBlobs(scene):
- blobs = cv.detectBlobs(scene, minArea=500, maxArea=5000, minCircularity=0.8)
+ blobs = cv.findBlobs(scene, minArea=500, maxArea=5000, minCircularity=0.8)
assert blobs.shape == (2, 3)
assert blobs[0, 2] >= blobs[1, 2] # largest first
assert abs(blobs[0, 0] - 80) <= 2 and abs(blobs[0, 1] - 80) <= 2
- assert cv.detectBlobs(255 - scene, minArea=500, minCircularity=0.8).shape == (0, 3) # the discs are light now
- assert cv.detectBlobs(255 - scene, minArea=500, dark=False, minCircularity=0.8).shape == (2, 3)
+ assert cv.findBlobs(255 - scene, minArea=500, minCircularity=0.8).shape == (0, 3) # the discs are light now
+ assert cv.findBlobs(255 - scene, minArea=500, dark=False, minCircularity=0.8).shape == (2, 3)
@pytest.mark.parametrize(
@@ -125,7 +126,7 @@ def test_detectBlobs(scene):
)
def test_detectBlobs_validation(scene, kwargs):
with pytest.raises(ValueError):
- cv.detectBlobs(scene, **kwargs)
+ cv.findBlobs(scene, **kwargs)
# --- binarize / morphology -----------------------------------------------------------
@@ -199,16 +200,16 @@ def test_applyMask():
cv.applyMask(img, mask[:2])
-def test_centerCrop():
+def test_cropCenter():
img = np.arange(100 * 60).reshape(60, 100).astype(np.uint8)
- out = cv.centerCrop(img, 20)
+ out = cv.cropCenter(img, 20)
assert out.shape == (20, 20)
np.testing.assert_array_equal(out, img[20:40, 40:60])
- assert cv.centerCrop(img, (30, 10)).shape == (10, 30)
- assert cv.centerCrop(img, (200, 10)).shape == (10, 100) # clipped
- assert cv.centerCrop(img, (200, 10), fill=0).shape == (10, 200) # padded
+ assert cv.cropCenter(img, (30, 10)).shape == (10, 30)
+ assert cv.cropCenter(img, (200, 10)).shape == (10, 100) # clipped
+ assert cv.cropCenter(img, (200, 10), fill=0).shape == (10, 200) # padded
with pytest.raises(ValueError, match="size"):
- cv.centerCrop(img, 0)
+ cv.cropCenter(img, 0)
# --- drawing -------------------------------------------------------------------------
@@ -299,6 +300,13 @@ def test_matchFeatures_validation(photo, kwargs):
cv.matchFeatures(photo, photo, **kwargs)
+def test_matchFeatures_masks(photo):
+ mask = np.zeros(photo.shape[:2], np.uint8)
+ mask[:, : photo.shape[1] // 2] = 255
+ found = cv.matchFeatures(photo, photo, mask=mask, referenceMask=mask)
+ assert found.srcPoints[:, 0].max() <= photo.shape[1] // 2 + 20
+
+
@pytest.mark.parametrize("motion", ["homography", "affine", "similarity"])
def test_alignImages_recovers_a_rotated_image(photo, motion):
rotated = cv.rotateEx(photo, 6)
diff --git a/tests/test_compose.py b/tests/test_compose.py
index 0fb8e84..c0e1e20 100644
--- a/tests/test_compose.py
+++ b/tests/test_compose.py
@@ -72,14 +72,14 @@ def test_overlayImage_opaque(background):
assert (background == 100).all() # src is not modified
-def test_overlayImage_alpha_and_opacity(background):
+def test_overlayImage_alpha_channel_and_alpha(background):
logo = np.zeros((1, 2, 4), np.uint8)
logo[0, 0] = (200, 200, 200, 255) # opaque
logo[0, 1] = (200, 200, 200, 0) # fully transparent
out = cv.overlayImage(background, logo)
assert tuple(out[0, 0]) == (200, 200, 200)
assert tuple(out[0, 1]) == (100, 100, 100)
- half = cv.overlayImage(background, logo, opacity=0.5)
+ half = cv.overlayImage(background, logo, alpha=0.5)
assert tuple(half[0, 0]) == (150, 150, 150)
@@ -106,7 +106,8 @@ def test_overlayImage_gray_and_bgra_targets():
[
(np.zeros((4, 4), np.float32), np.zeros((2, 2), np.uint8), {}, "8-bit"),
(np.zeros((4, 4), np.uint8), np.zeros((2, 2, 2), np.uint8), {}, "channels"),
- (np.zeros((4, 4), np.uint8), np.zeros((2, 2), np.uint8), {"opacity": 1.5}, "opacity"),
+ (np.zeros((4, 4), np.uint8), np.zeros((2, 2), np.uint8), {"alpha": 1.5}, "alpha"),
+ (np.zeros((4, 4), np.uint8), np.zeros((2, 2), np.uint8), {"alpha": float("nan")}, "alpha"),
],
)
def test_overlayImage_validation(src, overlay, kwargs, match):
diff --git a/tests/test_contour.py b/tests/test_contour.py
index 24c7fce..a0e60c6 100644
--- a/tests/test_contour.py
+++ b/tests/test_contour.py
@@ -214,12 +214,12 @@ def test_cropContour_blanks_the_outside(contours):
assert crop.shape == (51, 51, 3)
assert tuple(crop[0, 0]) == (0, 0, 0) # the corner of the box lies outside the circle
assert tuple(crop[25, 25]) == (200, 200, 200)
- assert tuple(cv.cropContour(img, contours[1], background=(1, 2, 3))[0, 0]) == (1, 2, 3)
+ assert tuple(cv.cropContour(img, contours[1], fill=(1, 2, 3))[0, 0]) == (1, 2, 3)
-def test_cropContour_margin_is_clipped_and_background_none_keeps_pixels(contours):
+def test_cropContour_margin_is_clipped_and_fill_none_keeps_pixels(contours):
img = np.full((120, 160), 200, np.uint8)
- crop = cv.cropContour(img, contours[1], margin=100, background=None)
+ crop = cv.cropContour(img, contours[1], margin=100, fill=None)
assert crop.shape == (120, 160)
assert crop.min() == 200
assert cv.cropContour(img, contours[0], margin=5).shape == (61, 61)
@@ -245,6 +245,7 @@ def test_cropContour_does_not_modify_the_source(contours):
[
({"margin": -1}, "margin"),
({"transparent": True}, "8-bit"),
+ ({"fill": float("nan")}, "fill"),
],
)
def test_cropContour_validation(contours, kwargs, match):
@@ -262,17 +263,25 @@ def test_cropContour_outside_the_image(contours):
def test_drawContoursEx_uses_a_different_color_per_contour(shapes, contours):
- out = cv.drawContoursEx(shapes, contours, thickness=cv.FILLED)
- assert out.shape == (120, 160, 3)
+ img = cv.toBGR(shapes)
+ out = cv.drawContoursEx(img, contours, thickness=cv.FILLED)
+ assert out is img # drawn in place, like cv.drawContours
colors = {tuple(out[45, 45]), tuple(out[45, 115]), tuple(out[102, 80])}
assert len(colors) == 3
- assert shapes.ndim == 2 # the source is not modified
+ assert colors == {tuple(c) for c in cv.distinctColors(3)}
+
+
+def test_drawContoursEx_gray_stays_gray(shapes, contours):
+ img = shapes.copy()
+ out = cv.drawContoursEx(img, contours, thickness=cv.FILLED)
+ assert out is img and out.ndim == 2
+ assert out[45, 45] != out[45, 115] # the luminance of each color
def test_drawContoursEx_labels(shapes, contours):
- plain = cv.drawContoursEx(shapes, contours)
- numbered = cv.drawContoursEx(shapes, contours, labels=True)
- named = cv.drawContoursEx(shapes, contours, labels=["a", "b", "c"])
+ plain = cv.drawContoursEx(cv.toBGR(shapes), contours)
+ numbered = cv.drawContoursEx(cv.toBGR(shapes), contours, labels=True)
+ named = cv.drawContoursEx(cv.toBGR(shapes), contours, labels=["a", "b", "c"])
assert (numbered != plain).any()
assert (named != plain).any()
@@ -290,3 +299,9 @@ def test_drawContoursEx_validation(shapes, contours):
cv.drawContoursEx(shapes, contours, labels=["only one"])
with pytest.raises(ValueError, match="8-bit"):
cv.drawContoursEx(shapes.astype(np.float32), contours)
+ with pytest.raises(ValueError, match="fontScale"):
+ cv.drawContoursEx(shapes, contours, fontScale=0)
+ with pytest.raises(ValueError, match="colors"):
+ cv.drawContoursEx(shapes, contours, colors=[])
+ with pytest.raises(ValueError, match="empty"):
+ cv.drawContoursEx(np.zeros((0, 4), np.uint8), contours)
diff --git a/tests/test_cv2u.py b/tests/test_cv2u.py
index 38dab30..6d286ad 100644
--- a/tests/test_cv2u.py
+++ b/tests/test_cv2u.py
@@ -139,32 +139,56 @@ def test_dbscan_roundtrip():
pytest.importorskip("sklearn")
src = np.zeros((8, 8, 3), np.uint8)
src[:, 4:] = (200, 50, 10)
- maps, labels = cv.DBSCAN(src, 1.7, 2)
- assert maps.shape == (8, 8)
- assert len(np.unique(labels)) == 2
- dst = cv.drawDBSCAN(src, maps, labels)
+ maps, centers = cv.dbscanColors(src, 1.7, 2)
+ assert isinstance(cv.dbscanColors(src, 1.7, 2), cv.Clusters)
+ assert maps.shape == (8, 8) and maps.dtype == np.int32
+ assert sorted(np.unique(maps).tolist()) == [0, 1] # labels start at 0; -1 would be noise
+ assert centers.shape == (2, 3) and centers.dtype == np.uint8
+ assert {tuple(c) for c in centers} == {(0, 0, 0), (200, 50, 10)}
+ dst = cv.drawClusters(src, maps)
assert dst.shape == src.shape
np.testing.assert_array_equal(dst, src)
+def test_dbscan_noise_is_minus_one():
+ pytest.importorskip("sklearn")
+ src = np.zeros((6, 6, 3), np.uint8)
+ src[2, 2] = (255, 255, 255) # a lone pixel is noise with minSamples=4
+ maps, centers = cv.dbscanColors(src, 1.7)
+ assert maps[2, 2] == -1
+ assert len(centers) == 1 and maps.max() == 0
+ painted = cv.drawClusters(src, maps)
+ assert tuple(painted[2, 2]) == (255, 255, 255) # noise keeps its original color
+
+
def test_dbscan_without_cluster_extra(monkeypatch, bgr):
# Simulate an install without the ``cluster`` extra.
monkeypatch.setitem(sys.modules, "sklearn", None)
monkeypatch.setitem(sys.modules, "sklearn.cluster", None)
with pytest.raises(ImportError, match=r"python-opencv-utils\[cluster\]"):
- cv.DBSCAN(bgr, 1.7, 2)
+ cv.dbscanColors(bgr, 1.7, 2)
-@pytest.mark.parametrize("src", [np.zeros((8, 8), np.uint8), np.zeros((8, 8, 4), np.uint8), [[1, 2, 3]]])
+@pytest.mark.parametrize("src", [np.zeros((8, 8), np.uint8), np.zeros((8, 8, 4), np.uint8), np.zeros((1, 3), np.uint8)])
def test_dbscan_rejects_non_bgr(src):
with pytest.raises(ValueError, match="3-channel"):
- cv.DBSCAN(src, 1.7, 2)
+ cv.dbscanColors(src, 1.7, 2)
-def test_drawDBSCAN_rejects_mismatched_maps(bgr):
- labels = np.zeros(10, dtype=np.int64)
- with pytest.raises(ValueError, match="do not match"):
- cv.drawDBSCAN(bgr, labels.reshape(2, 5), labels)
+def test_dbscan_validation(bgr):
+ with pytest.raises(ValueError, match="uint8"):
+ cv.dbscanColors(bgr.astype(np.float32), 1.7)
+ with pytest.raises(ValueError, match="empty"):
+ cv.dbscanColors(np.zeros((0, 0, 3), np.uint8), 1.7)
+ with pytest.raises(ValueError, match="eps"):
+ cv.dbscanColors(bgr, 0)
+ with pytest.raises(ValueError, match="minSamples"):
+ cv.dbscanColors(bgr, 1.7, minSamples=0)
+
+
+def test_drawClusters_rejects_mismatched_maps(bgr):
+ with pytest.raises(ValueError, match="maps"):
+ cv.drawClusters(bgr, np.zeros((2, 5), dtype=np.int64))
def test_gammaCorrection(bgr):
@@ -234,51 +258,62 @@ def test_isInside_matches_pointPolygonTest():
assert cv.isInside((x, y), star) == (expected > 0), (x, y)
-def test_DHEdge(bgr):
+def test_boldEdges(bgr):
gray = cv.cvtColor(bgr, cv.COLOR_BGR2GRAY)
- dst = cv.DHEdge(gray)
+ dst = cv.boldEdges(gray)
assert dst.shape == gray.shape
assert dst.dtype == np.uint8
-def test_DHEdge_flat_image_has_no_edges():
+def test_boldEdges_flat_image_has_no_edges():
# Including the 1-pixel border, which must not keep the source intensity.
- assert not cv.DHEdge(np.full((10, 12), 100, np.uint8)).any()
+ assert not cv.boldEdges(np.full((10, 12), 100, np.uint8)).any()
-def test_DHEdge_color(bgr):
- assert cv.DHEdge(bgr).shape == bgr.shape
+def test_boldEdges_color(bgr):
+ assert cv.boldEdges(bgr).shape == bgr.shape
-def test_DHEdge_validation():
+def test_boldEdges_validation():
with pytest.raises(ValueError, match="uint8"):
- cv.DHEdge(np.zeros((8, 8), np.float32))
+ cv.boldEdges(np.zeros((8, 8), np.float32))
+ with pytest.raises(ValueError, match="empty"):
+ cv.boldEdges(np.zeros((0, 8), np.uint8))
def test_makeGradient_bgr():
- img = cv.makeGradient((10, 20, 3), (0, 0, 0), (255, 128, 64))
+ img = cv.makeGradient((20, 10), (0, 0, 0), (255, 128, 64))
assert img.shape == (10, 20, 3)
assert img.dtype == np.uint8
assert tuple(img[0, 0]) == (0, 0, 0)
assert tuple(img[-1, -1]) == (255, 128, 64)
-@pytest.mark.parametrize("shape", [(10, 20), (10, 20, 1)])
@pytest.mark.parametrize(("start", "end"), [(0, 255), ((0,), (255,))])
-def test_makeGradient_gray(shape, start, end):
- img = cv.makeGradient(shape, start, end)
- assert img.shape == shape
+def test_makeGradient_gray(start, end):
+ img = cv.makeGradient((20, 10), start, end, channels=1)
+ assert img.shape == (10, 20)
assert img.flat[0] == 0
assert img.flat[-1] == 255
-def test_makeGradient_invalid_channels():
- with pytest.raises(ValueError, match="channels"):
- cv.makeGradient((10, 10, 4), 0, 255)
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"size": (10, 10), "start": 0, "end": 255, "channels": 4},
+ {"size": (0, 10), "start": 0, "end": 255},
+ {"size": (10, 10), "start": -1, "end": 255},
+ {"size": (10, 10), "start": 0, "end": float("nan")},
+ {"size": (10, 10), "start": (0, 0), "end": 255},
+ ],
+)
+def test_makeGradient_validation(kwargs):
+ with pytest.raises(ValueError):
+ cv.makeGradient(**kwargs)
def test_makeGradient_horizontal():
- img = cv.makeGradient((4, 256, 3), (0, 0, 0), (255, 255, 255), direction="horizontal")
+ img = cv.makeGradient((256, 4), (0, 0, 0), (255, 255, 255), direction="horizontal")
assert img.shape == (4, 256, 3)
np.testing.assert_array_equal(img[0], img[-1]) # every row is the same
assert img[0, 0, 0] == 0
@@ -287,7 +322,7 @@ def test_makeGradient_horizontal():
def test_makeGradient_vertical():
- img = cv.makeGradient((256, 4), 0, 255, direction="vertical")
+ img = cv.makeGradient((4, 256), 0, 255, direction="vertical", channels=1)
assert img.shape == (256, 4)
np.testing.assert_array_equal(img[:, 0], img[:, -1]) # every column is the same
assert img[0, 0] == 0
@@ -296,12 +331,12 @@ def test_makeGradient_vertical():
def test_makeGradient_horizontal_is_default():
np.testing.assert_array_equal(
- cv.makeGradient((10, 20, 3), 0, 255), cv.makeGradient((10, 20, 3), 0, 255, direction="horizontal")
+ cv.makeGradient((20, 10), 0, 255), cv.makeGradient((20, 10), 0, 255, direction="horizontal")
)
def test_makeGradient_raster():
- img = cv.makeGradient((2, 3), 0, 250, direction="raster")
+ img = cv.makeGradient((3, 2), 0, 250, direction="raster", channels=1)
np.testing.assert_array_equal(img, [[0, 50, 100], [150, 200, 250]])
@@ -311,8 +346,28 @@ def test_makeGradient_invalid_direction():
def test_imcolor(bgr):
- assert tuple(cv.imcolor((5, 5, 3), (1, 2, 3))[2, 2]) == (1, 2, 3)
- assert cv.imcolor((2, 2), 0.5, dtype=np.float32).dtype == np.float32
+ img = cv.imcolor((5, 4), (1, 2, 3))
+ assert img.shape == (4, 5, 3) and img.dtype == np.uint8
+ assert tuple(img[2, 2]) == (1, 2, 3)
+ assert cv.imcolor((2, 3), 0.5, channels=1, dtype=np.float32).shape == (3, 2)
+ assert cv.imcolor((2, 2), 0.5, channels=1, dtype=np.float32).dtype == np.float32
+ assert tuple(cv.imcolor((2, 2), (1, 2, 3, 4), channels=4)[0, 0]) == (1, 2, 3, 4)
+ assert tuple(cv.imcolor((2, 2), 9)[0, 0]) == (9, 9, 9)
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"size": (0, 2), "color": 0},
+ {"size": (2, 2), "color": 0, "channels": 2},
+ {"size": (2, 2), "color": 256},
+ {"size": (2, 2), "color": float("inf")},
+ {"size": (2, 2), "color": (1, 2)},
+ ],
+)
+def test_imcolor_validation(kwargs):
+ with pytest.raises(ValueError):
+ cv.imcolor(**kwargs)
def test_imcolorLike(bgr):
@@ -322,28 +377,40 @@ def test_imcolorLike(bgr):
assert tuple(like[0, 0]) == (1, 2, 3)
assert cv.imcolorLike(np.zeros((2, 2), np.float32), 0.5).dtype == np.float32
assert cv.imcolorLike(np.zeros((2, 2), np.float32), 7, dtype=np.uint8).dtype == np.uint8
+ with pytest.raises(ValueError, match="color"):
+ cv.imcolorLike(bgr, 300)
+ with pytest.raises(ValueError, match="color"):
+ cv.imcolorLike(bgr, (1, 2))
+ with pytest.raises(ValueError, match="color"):
+ cv.imcolorLike(np.zeros((2, 2), np.float32), float("nan"))
# --- imgcodecs -------------------------------------------------------------------
-def test_urlread_file_url(tmp_path, bgr):
+def test_imreadUrl_file_url(tmp_path, bgr):
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
- np.testing.assert_array_equal(cv.urlread(path.as_uri()), bgr)
+ np.testing.assert_array_equal(cv.imreadUrl(path.as_uri()), bgr)
+
+
+def test_imreadUrl_reads_color_by_default_like_imread(tmp_path):
+ path = tmp_path / "img.png"
+ assert cv.imwrite(str(path), np.zeros((4, 4, 4), np.uint8))
+ assert cv.imreadUrl(path.as_uri()).shape == (4, 4, 3)
+ assert cv.imreadUrl(path.as_uri(), cv.IMREAD_UNCHANGED).shape == (4, 4, 4)
-def test_urlread_undecodable_returns_none(tmp_path):
+def test_imreadUrl_undecodable_returns_none(tmp_path):
path = tmp_path / "not-an-image.png"
path.write_bytes(b"hello")
- assert cv.urlread(path.as_uri()) is None
+ assert cv.imreadUrl(path.as_uri()) is None
-def test_urlread_sends_headers(monkeypatch, tmp_path, bgr):
+def test_imreadUrl_sends_headers(monkeypatch, tmp_path, bgr):
import urllib.request
- # ``cv2u.imgcodecs.urlread`` is the re-exported function, so take the module from sys.modules.
- urlread_module = sys.modules["cv2u.imgcodecs.urlread"]
+ urlread_module = sys.modules["cv2u.imgcodecs.url"]
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
@@ -356,12 +423,12 @@ def spy(request, timeout=None):
return real_urlopen(request, timeout=timeout)
monkeypatch.setattr(urlread_module, "urlopen", spy)
- cv.urlread(path.as_uri(), timeout=5, headers={"X-Test": "1"})
+ cv.imreadUrl(path.as_uri(), timeout=5, headers={"X-Test": "1"})
assert seen["User-agent"].startswith("cv2u")
assert seen["X-test"] == "1"
assert seen["timeout"] == 5
- cv.urlread(path.as_uri(), headers={"User-Agent": "custom"})
+ cv.imreadUrl(path.as_uri(), headers={"User-Agent": "custom"})
assert seen["User-agent"] == "custom"
@@ -378,8 +445,7 @@ def test_flip_flags(bgr):
def test_putTextEx(bgr, gray_input, font_path):
font = font_path
src = np.zeros((40, 60), np.uint8) if gray_input else np.zeros_like(bgr)
- before = src.copy()
dst = cv.putTextEx(src, "Hi 한글", (2, 2), font, 20, (255, 255, 255)) # pathlib.Path is accepted
- assert dst.shape == (40, 60, 3)
+ assert dst is src # drawn in place, like cv.putText
+ assert dst.shape == src.shape # grayscale stays grayscale
assert dst.any()
- np.testing.assert_array_equal(src, before) # src is not modified
diff --git a/tests/test_expected.py b/tests/test_expected.py
index 6a8d10c..3d3fbc4 100644
--- a/tests/test_expected.py
+++ b/tests/test_expected.py
@@ -196,11 +196,13 @@ def test_matchTemplate_only_returns_a_score_map(scene):
def test_findTemplate_finds_every_copy(scene):
img, patch = scene
matches = cv.findTemplate(img, patch)
- assert sorted((x, y) for x, y, *_ in matches) == [(10, 20), (50, 90), (90, 30)]
- assert all(w == 16 and h == 12 for _, _, w, h, _ in matches)
- scores = [s for *_, s in matches]
+ assert matches.shape == (3, 5) and matches.dtype == np.float64
+ assert sorted((x, y) for x, y, *_ in matches.tolist()) == [(10, 20), (50, 90), (90, 30)]
+ assert (matches[:, 2] == 16).all() and (matches[:, 3] == 12).all()
+ scores = matches[:, 4].tolist()
assert scores == sorted(scores, reverse=True)
assert scores[0] == pytest.approx(1.0, abs=1e-4)
+ assert cv.findTemplate(img, patch, threshold=1.0, maxCount=0).shape == (0, 5) # always an array
def test_findTemplate_maxCount_and_threshold(scene):
@@ -213,7 +215,7 @@ def test_findTemplate_maxCount_and_threshold(scene):
def test_findTemplate_other_methods(scene, method):
img, patch = scene
matches = cv.findTemplate(img, patch, threshold=0.95, method=method)
- assert (10, 20) in [(x, y) for x, y, *_ in matches]
+ assert (10, 20) in [(x, y) for x, y, *_ in matches.tolist()]
def test_findTemplate_mixed_channels(scene):
@@ -224,7 +226,14 @@ def test_findTemplate_mixed_channels(scene):
@pytest.mark.parametrize(
("kwargs", "templ_shape"),
- [({"method": cv2.TM_CCOEFF}, (4, 4)), ({"threshold": 1.5}, (4, 4)), ({}, (200, 10))],
+ [
+ ({"method": cv2.TM_CCOEFF}, (4, 4)),
+ ({"threshold": 1.5}, (4, 4)),
+ ({"threshold": float("nan")}, (4, 4)),
+ ({"maxCount": -1}, (4, 4)),
+ ({}, (200, 10)),
+ ({}, (0, 4)),
+ ],
)
def test_findTemplate_validation(scene, kwargs, templ_shape):
img, _ = scene
diff --git a/tests/test_geometry_color_hash.py b/tests/test_geometry_color_hash.py
index 87f60e0..501cdd6 100644
--- a/tests/test_geometry_color_hash.py
+++ b/tests/test_geometry_color_hash.py
@@ -51,9 +51,27 @@ def test_cropRotatedRect_extracts_the_box(angle):
assert crop[2:-2, 2:-2].min() > 200 # the inside is all box, no background
-def test_cropRotatedRect_validation():
+def test_cropRotatedRect_fills_the_outside_with_borderValue():
+ img = np.full((20, 20), 200, np.uint8)
+ crop = cv.cropRotatedRect(img, ((2, 10), (10, 4), 0)) # half of the box lies left of the image
+ assert crop.shape == (4, 10)
+ assert crop[:, 0].max() == 0 # BORDER_CONSTANT with 0 by default, not a replicated edge
+ assert crop[:, -1].min() == 200
+ assert cv.cropRotatedRect(img, ((2, 10), (10, 4), 0), borderValue=7)[0, 0] == 7
+
+
+@pytest.mark.parametrize(
+ ("src", "rect"),
+ [
+ (np.zeros((10, 10), np.uint8), ((5, 5), (0.2, 4), 0)),
+ (np.zeros((0, 10), np.uint8), ((5, 5), (4, 4), 0)),
+ (np.zeros((10, 10), np.uint8), ((float("nan"), 5), (4, 4), 0)),
+ (np.zeros((10, 10), np.uint8), ((5, 5), (4, 4), float("inf"))),
+ ],
+)
+def test_cropRotatedRect_validation(src, rect):
with pytest.raises(ValueError):
- cv.cropRotatedRect(np.zeros((10, 10), np.uint8), ((5, 5), (0.2, 4), 0))
+ cv.cropRotatedRect(src, rect)
# --- deskew ----------------------------------------------------------------------
@@ -138,7 +156,7 @@ def test_flattenAlpha_composites_on_the_background():
assert tuple(out[1, 0]) == (127, 127, 127)
assert tuple(cv.flattenAlpha(bgra, (0, 255, 0))[0, 1]) == (0, 255, 0)
background = np.full((2, 2), 10, np.uint8)
- assert tuple(cv.flattenAlpha(bgra, background)[0, 1]) == (10, 10, 10)
+ assert tuple(cv.flattenAlpha(bgra, fill=background)[0, 1]) == (10, 10, 10)
def test_flattenAlpha_other_inputs():
@@ -155,7 +173,7 @@ def test_flattenAlpha_other_inputs():
@pytest.mark.parametrize("method", ["difference", "average", "perceptual"])
def test_imageHash_near_duplicates_are_close(method):
- img = cv.makeGradient((120, 160, 3), (0, 0, 0), (255, 200, 100))
+ img = cv.makeGradient((160, 120), (0, 0, 0), (255, 200, 100))
cv.circle(img, (60, 50), 25, (0, 0, 255), -1)
cv.rectangle(img, (100, 70), (150, 110), (255, 255, 0), -1)
resized = cv.resize(img, (80, 60), interpolation=cv.INTER_AREA)
@@ -212,7 +230,7 @@ def test_drawRoundedRectangle_outline_and_fill():
assert img[25, 35] == 0 # outline only
filled = np.zeros((60, 80, 3), np.uint8)
- cv.drawRoundedRectangle(filled, (10, 10, 50, 30), (0, 255, 0), cv.FILLED, cv.LINE_AA, radius=8)
+ cv.drawRoundedRectangle(filled, (10, 10, 50, 30), (0, 255, 0), cv.FILLED, 8, cv.LINE_AA)
assert tuple(filled[25, 35]) == (0, 255, 0)
assert tuple(filled[10, 10]) == (0, 0, 0)
square = np.zeros((60, 80), np.uint8)
@@ -228,6 +246,8 @@ def test_drawRoundedRectangle_small_box_and_validation():
cv.drawRoundedRectangle(img, (0, 0, 0, 5), 255)
with pytest.raises(ValueError):
cv.drawRoundedRectangle(img, (0, 0, 5, 5), 255, radius=-1)
+ with pytest.raises(ValueError, match="empty"):
+ cv.drawRoundedRectangle(np.zeros((0, 5), np.uint8), (0, 0, 5, 5), 255)
# --- pixelate --------------------------------------------------------------------
diff --git a/tests/test_golden.py b/tests/test_golden.py
index 5a7c403..70ea957 100644
--- a/tests/test_golden.py
+++ b/tests/test_golden.py
@@ -47,15 +47,15 @@ def test_gammaCorrection(rotate_src):
_assert_close(cv.gammaCorrection(rotate_src, 2.2), _read("gammaCorrection_2.2.png"), max_abs=0)
-def test_DHEdge(rotate_src):
+def test_boldEdges(rotate_src):
gray = cv.cvtColor(rotate_src, cv.COLOR_BGR2GRAY)
- # DHEdge amplifies differences by pi, so allow a little more slack.
- _assert_close(cv.DHEdge(gray), _read("DHEdge.png"), max_abs=4, max_mismatch_ratio=0.001)
+ # boldEdges amplifies differences by pi, so allow a little more slack.
+ _assert_close(cv.boldEdges(gray), _read("boldEdges.png"), max_abs=4, max_mismatch_ratio=0.001)
-def test_drawDBSCAN():
+def test_drawClusters():
pytest.importorskip("sklearn")
src = _read("dbscan_src.png")
- maps, labels = cv.DBSCAN(src, 1.7, 2)
+ maps, _ = cv.dbscanColors(src, 1.7, 2)
# A +-1 difference in the Lab conversion can move a few border pixels to another cluster.
- _assert_close(cv.drawDBSCAN(src, maps, labels), _read("drawDBSCAN.png"), max_abs=2, max_mismatch_ratio=0.01)
+ _assert_close(cv.drawClusters(src, maps), _read("drawClusters.png"), max_abs=2, max_mismatch_ratio=0.01)
diff --git a/tests/test_imgproc_extra.py b/tests/test_imgproc_extra.py
index 75c6b0a..fc961c1 100644
--- a/tests/test_imgproc_extra.py
+++ b/tests/test_imgproc_extra.py
@@ -35,7 +35,16 @@ def test_autoCanny_finds_the_shapes(shapes):
assert not edges[100:, :].any() # nothing below the shapes
-@pytest.mark.parametrize(("src", "sigma"), [(np.zeros((4, 4), np.float32), 0.33), (np.zeros((4, 4), np.uint8), 1.5)])
+def test_autoCanny_accepts_16_bit_and_float_images(shapes):
+ # Stretched to 8 bits first: cv.Canny itself rejects anything but uint8.
+ np.testing.assert_array_equal(cv.autoCanny(shapes.astype(np.uint16) * 257), cv.autoCanny(shapes))
+ np.testing.assert_array_equal(cv.autoCanny(shapes.astype(np.float32) / 255), cv.autoCanny(shapes))
+
+
+@pytest.mark.parametrize(
+ ("src", "sigma"),
+ [(np.zeros((0, 4), np.uint8), 0.33), (np.zeros((4, 4), np.uint8), 1.5), (np.zeros((4, 4, 2)), 0.3)],
+)
def test_autoCanny_validation(src, sigma):
with pytest.raises(ValueError):
cv.autoCanny(src, sigma=sigma)
diff --git a/tests/test_peaks.py b/tests/test_peaks.py
index 10f8a43..a6d30d8 100644
--- a/tests/test_peaks.py
+++ b/tests/test_peaks.py
@@ -75,10 +75,10 @@ def test_peakColors_minRegion_removes_speckles():
assert len(centers) == 2
-def test_peakColors_works_with_drawDBSCAN():
+def test_peakColors_works_with_drawClusters():
img = _three_colors()
maps, _ = cv.peakColors(img)
- assert len(np.unique(cv.drawDBSCAN(img, maps, maps.ravel()).reshape(-1, 3), axis=0)) == 3
+ assert len(np.unique(cv.drawClusters(img, maps).reshape(-1, 3), axis=0)) == 3
def test_peakColors_needs_no_extra(monkeypatch):
diff --git a/tests/test_resize.py b/tests/test_resize.py
index eef54b5..003614b 100644
--- a/tests/test_resize.py
+++ b/tests/test_resize.py
@@ -44,7 +44,10 @@ def test_resizeEx_validation(img, kwargs):
def test_letterbox_shape_scale_and_offset(img):
- dst, scale, (left, top) = cv.letterbox(img, (300, 300), color=(1, 2, 3))
+ result = cv.letterbox(img, (300, 300), color=(1, 2, 3))
+ assert isinstance(result, cv.Letterbox)
+ assert result.image is result[0] and result.scale == result[1] and result.offset == result[2]
+ dst, scale, (left, top) = result
assert dst.shape == (300, 300, 3)
assert scale == pytest.approx(1.5)
assert (left, top) == (0, 75)
diff --git a/tests/test_roi.py b/tests/test_roi.py
index aa83bf8..f6eba1f 100644
--- a/tests/test_roi.py
+++ b/tests/test_roi.py
@@ -9,54 +9,63 @@ def img():
return np.arange(100, dtype=np.uint8).reshape(10, 10)
-# --- cropEx ------------------------------------------------------------------------
+# --- cropRect ------------------------------------------------------------------------
-def test_cropEx_inside_matches_slicing(img):
- np.testing.assert_array_equal(cv.cropEx(img, (2, 3, 4, 5)), img[3:8, 2:6])
+def test_cropRect_inside_matches_slicing(img):
+ np.testing.assert_array_equal(cv.cropRect(img, (2, 3, 4, 5)), img[3:8, 2:6])
-def test_cropEx_returns_a_copy(img):
- crop = cv.cropEx(img, (0, 0, 2, 2))
+def test_cropRect_returns_a_copy(img):
+ crop = cv.cropRect(img, (0, 0, 2, 2))
crop[:] = 0
assert img[0, 1] == 1
-def test_cropEx_negative_coordinates_are_clipped(img):
+def test_cropRect_negative_coordinates_are_clipped(img):
# Plain slicing img[-2:3, -2:3] would return an empty array here.
- np.testing.assert_array_equal(cv.cropEx(img, (-2, -2, 5, 5)), img[0:3, 0:3])
+ np.testing.assert_array_equal(cv.cropRect(img, (-2, -2, 5, 5)), img[0:3, 0:3])
-def test_cropEx_fill_keeps_the_box_size(img):
- crop = cv.cropEx(img, (-2, 8, 4, 4), fill=255)
+def test_cropRect_fill_keeps_the_box_size(img):
+ crop = cv.cropRect(img, (-2, 8, 4, 4), fill=255)
assert crop.shape == (4, 4)
np.testing.assert_array_equal(crop[:2, 2:], img[8:10, 0:2])
assert (crop[:, :2] == 255).all()
assert (crop[2:, :] == 255).all()
-def test_cropEx_fill_color_image():
+def test_cropRect_fill_color_image():
bgr = np.zeros((5, 5, 3), np.uint8)
- crop = cv.cropEx(bgr, (3, 3, 4, 4), fill=(1, 2, 3))
+ crop = cv.cropRect(bgr, (3, 3, 4, 4), fill=(1, 2, 3))
assert crop.shape == (4, 4, 3)
assert tuple(crop[3, 3]) == (1, 2, 3)
assert tuple(crop[0, 0]) == (0, 0, 0)
-def test_cropEx_margin(img):
- np.testing.assert_array_equal(cv.cropEx(img, (4, 4, 2, 2), margin=1), img[3:7, 3:7])
+def test_cropRect_margin(img):
+ np.testing.assert_array_equal(cv.cropRect(img, (4, 4, 2, 2), margin=1), img[3:7, 3:7])
-def test_cropEx_outside(img):
- assert cv.cropEx(img, (20, 20, 3, 3)).size == 0
- assert (cv.cropEx(img, (20, 20, 3, 3), fill=7) == 7).all()
+def test_cropRect_outside_raises(img):
+ # Before: an empty array (or a box full of fill), which failed later with an unrelated error.
+ with pytest.raises(ValueError, match="outside"):
+ cv.cropRect(img, (20, 20, 3, 3))
+ with pytest.raises(ValueError, match="outside"):
+ cv.cropRect(img, (20, 20, 3, 3), fill=7)
+ with pytest.raises(ValueError, match="outside"):
+ cv.cropRect(img, (-5, 0, 5, 5)) # touches the border without covering a pixel
-def test_cropEx_validation(img):
- with pytest.raises(ValueError):
- cv.cropEx(img, (0, 0, 0, 5))
- with pytest.raises(ValueError):
- cv.cropEx(img, (0, 0, 4, 4), margin=-2)
+def test_cropRect_validation(img):
+ with pytest.raises(ValueError, match="rect"):
+ cv.cropRect(img, (0, 0, 0, 5))
+ with pytest.raises(ValueError, match="rect"):
+ cv.cropRect(img, (0, 0, 4, 4), margin=-2)
+ with pytest.raises(ValueError, match="rect"):
+ cv.cropRect(img, (0, 0, float("nan"), 4))
+ with pytest.raises(ValueError, match="empty"):
+ cv.cropRect(np.zeros((0, 0), np.uint8), (0, 0, 4, 4))
# --- inRangeEx ---------------------------------------------------------------------
diff --git a/tests/test_validation.py b/tests/test_validation.py
index 4b13c45..e48d49a 100644
--- a/tests/test_validation.py
+++ b/tests/test_validation.py
@@ -15,6 +15,7 @@
IMG = np.zeros((40, 60, 3), np.uint8)
GRAY = np.zeros((40, 60), np.uint8)
EMPTY = np.zeros((0, 0, 3), np.uint8)
+CONTOUR = np.array([[[5, 5]], [[20, 5]], [[20, 20]], [[5, 20]]], np.int32)
# --- NaN and infinite numeric parameters ------------------------------------------
@@ -52,6 +53,35 @@
("toBGRA alpha", lambda v: cv.toBGRA(IMG, alpha=v)),
("writeVideo fps", lambda v: cv.writeVideo("x.avi", [IMG], fps=v)),
("fourPointTransform pts", lambda v: cv.fourPointTransform(IMG, [[0, 0], [10, 0], [10, 10], [0, v]])),
+ ("translate dx", lambda v: cv.translate(IMG, v, 0)),
+ ("translate dy", lambda v: cv.translate(IMG, 0, v)),
+ ("imcolor color", lambda v: cv.imcolor((4, 4), v)),
+ ("imcolorLike color", lambda v: cv.imcolorLike(IMG, v)),
+ ("makeGradient start", lambda v: cv.makeGradient((4, 4), v, 255)),
+ ("makeGradient end", lambda v: cv.makeGradient((4, 4), 0, (v, 0, 0))),
+ ("cropRotatedRect rect", lambda v: cv.cropRotatedRect(IMG, ((v, 5), (4, 4), 0))),
+ ("cropRect rect", lambda v: cv.cropRect(IMG, (0, 0, v, 4))),
+ ("dbscanColors eps", lambda v: cv.dbscanColors(IMG, v)),
+ ("clusterPoints eps", lambda v: cv.clusterPoints([[0, 0], [1, 1]], v)),
+ ("meanShiftColors bandwidth", lambda v: cv.meanShiftColors(IMG, bandwidth=v)),
+ ("peakColors minShare", lambda v: cv.peakColors(IMG, minShare=v)),
+ ("overlayImage alpha", lambda v: cv.overlayImage(IMG, IMG, alpha=v)),
+ ("overlayMask alpha", lambda v: cv.overlayMask(IMG, GRAY, alpha=v)),
+ ("nms iouThreshold", lambda v: cv.nms([[0, 0, 1, 1]], [1.0], iouThreshold=v)),
+ ("nms scoreThreshold", lambda v: cv.nms([[0, 0, 1, 1]], [1.0], scoreThreshold=v)),
+ ("expandBoxes margin", lambda v: cv.expandBoxes([0, 0, 1, 1], margin=v)),
+ ("findTemplate threshold", lambda v: cv.findTemplate(IMG, IMG[:4, :4], threshold=v)),
+ ("autoCanny sigma", lambda v: cv.autoCanny(GRAY, sigma=v)),
+ ("removeSmallObjects minArea", lambda v: cv.removeSmallObjects(GRAY, minArea=v)),
+ ("diffMask minArea", lambda v: cv.diffMask(IMG, IMG, minArea=v)),
+ ("applyMask fill", lambda v: cv.applyMask(IMG, GRAY, fill=v)),
+ ("cropContour fill", lambda v: cv.cropContour(IMG, CONTOUR, fill=v)),
+ ("flattenAlpha fill", lambda v: cv.flattenAlpha(np.zeros((4, 4, 4), np.uint8), fill=v)),
+ ("autoContrast clip", lambda v: cv.autoContrast(IMG, clip=v)),
+ ("drawLabel fontScale", lambda v: cv.drawLabel(IMG.copy(), (0, 0, 10, 10), "a", 255, fontScale=v)),
+ ("drawContoursEx fontScale", lambda v: cv.drawContoursEx(IMG.copy(), [CONTOUR], fontScale=v)),
+ ("deskew maxAngle", lambda v: cv.deskew(GRAY, maxAngle=v)),
+ ("inRangeEx lowerb", lambda v: cv.inRangeEx(IMG, (v, 0, 0), (10, 255, 255))),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -80,7 +110,21 @@ def test_rotateEx_rejects_non_positive_scale(scale):
("ssim dataRange", lambda: cv.ssim(IMG, IMG, dataRange=0)),
("equalizeHistEx clipLimit", lambda: cv.equalizeHistEx(IMG, clahe=True, clipLimit=0)),
("cutout feather", lambda: cv.cutout(IMG, GRAY, feather=-1)),
- ("urlread maxBytes", lambda: cv.urlread("file:///x.png", maxBytes=0)),
+ ("imreadUrl maxBytes", lambda: cv.imreadUrl("file:///x.png", maxBytes=0)),
+ ("kmeansColors maxIter", lambda: cv.kmeansColors(IMG, 2, maxIter=0)),
+ ("dbscanColors eps", lambda: cv.dbscanColors(IMG, 0)),
+ ("dbscanColors minSamples", lambda: cv.dbscanColors(IMG, 1.0, minSamples=0)),
+ ("meanShiftColors bandwidth", lambda: cv.meanShiftColors(IMG, bandwidth=0)),
+ ("nms iouThreshold", lambda: cv.nms([[0, 0, 1, 1]], [1.0], iouThreshold=1.5)),
+ ("makeGradient size", lambda: cv.makeGradient((0, 4), 0, 255)),
+ ("imcolor size", lambda: cv.imcolor((4, 0), 0)),
+ ("drawHistogram size", lambda: cv.drawHistogram(IMG, size=(0, 10))),
+ ("mergeTiles size", lambda: cv.mergeTiles([(IMG, (0, 0))], (0, 10))),
+ ("findTemplate maxCount", lambda: cv.findTemplate(IMG, IMG[:4, :4], maxCount=-1)),
+ ("findCircles minRadius", lambda: cv.findCircles(GRAY, minRadius=-1)),
+ ("findCircles maxRadius", lambda: cv.findCircles(GRAY, maxRadius=-1)),
+ ("cropRect rect", lambda: cv.cropRect(IMG, (0, 0, 0, 4))),
+ ("drawContoursEx fontScale", lambda: cv.drawContoursEx(IMG.copy(), [CONTOUR], fontScale=0)),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -89,6 +133,23 @@ def test_negative_or_zero_parameters_raise_value_error(name, call):
call()
+@pytest.mark.parametrize(
+ ("call", "match"),
+ [
+ (lambda: cv.findCircles(GRAY, minRadius=-1), "minRadius"),
+ (lambda: cv.findCircles(GRAY, maxRadius=-1), "maxRadius"),
+ (lambda: cv.filterContours([CONTOUR], minArea=float("nan")), "minArea must be a number"),
+ (lambda: cv.filterContours([CONTOUR], minArea=10, maxArea=5), "minArea must not exceed maxArea"),
+ (lambda: cv.filterContours([CONTOUR], minAspectRatio=2, maxAspectRatio=1), "minAspectRatio"),
+ (lambda: cv.cropRect(IMG, (0, 0, 0, 4)), "rect"),
+ (lambda: cv.cropRect(IMG, (100, 100, 4, 4)), "rect .* outside"),
+ ],
+)
+def test_messages_name_the_argument(call, match):
+ with pytest.raises(ValueError, match=match):
+ call()
+
+
# --- colors outside the dtype range ----------------------------------------------
@@ -99,6 +160,8 @@ def test_negative_or_zero_parameters_raise_value_error(name, call):
("hconcatEx", lambda c: cv.hconcatEx([IMG, GRAY], color=c)),
("letterbox", lambda c: cv.letterbox(IMG, (80, 80), color=c)),
("padToSize", lambda c: cv.padToSize(IMG, (80, 80), color=c)),
+ ("imcolor", lambda c: cv.imcolor((4, 4), c)),
+ ("imcolorLike", lambda c: cv.imcolorLike(IMG, c)),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -150,6 +213,52 @@ def test_float_images_accept_any_finite_color():
("peakColors", lambda: cv.peakColors(EMPTY)),
("hconcatEx", lambda: cv.hconcatEx([IMG, EMPTY])),
("overlayImage", lambda: cv.overlayImage(IMG, EMPTY)),
+ ("rotateEx", lambda: cv.rotateEx(EMPTY, 30)),
+ ("fourPointTransform", lambda: cv.fourPointTransform(EMPTY, [[0, 0], [10, 0], [10, 10], [0, 10]])),
+ ("padToMultiple", lambda: cv.padToMultiple(EMPTY, 32)),
+ ("padToSize", lambda: cv.padToSize(EMPTY, (10, 10))),
+ ("splitTiles", lambda: cv.splitTiles(EMPTY, (10, 10))),
+ ("mapTiles", lambda: cv.mapTiles(EMPTY, (10, 10), lambda t: t)),
+ ("gammaCorrection", lambda: cv.gammaCorrection(EMPTY, 2.2)),
+ ("boldEdges", lambda: cv.boldEdges(EMPTY)),
+ ("drawHistogram", lambda: cv.drawHistogram(EMPTY)),
+ ("drawLabel", lambda: cv.drawLabel(EMPTY, (0, 0, 1, 1), "a", 255)),
+ ("drawBoxes", lambda: cv.drawBoxes(EMPTY, [[0, 0, 1, 1]])),
+ ("drawPoints", lambda: cv.drawPoints(EMPTY, [[0, 0]])),
+ ("drawGrid", lambda: cv.drawGrid(EMPTY, 10)),
+ ("drawDashedLine", lambda: cv.drawDashedLine(EMPTY, (0, 0), (5, 5), 255)),
+ ("drawDashedRectangle", lambda: cv.drawDashedRectangle(EMPTY, (0, 0, 5, 5), 255)),
+ ("drawRoundedRectangle", lambda: cv.drawRoundedRectangle(EMPTY, (0, 0, 5, 5), 255)),
+ ("drawContoursEx", lambda: cv.drawContoursEx(EMPTY, [CONTOUR])),
+ ("overlayMask", lambda: cv.overlayMask(EMPTY, np.zeros((0, 0), np.uint8))),
+ ("findTemplate src", lambda: cv.findTemplate(EMPTY, IMG)),
+ ("findTemplate templ", lambda: cv.findTemplate(IMG, EMPTY)),
+ ("inRangeEx", lambda: cv.inRangeEx(EMPTY, (0, 0, 0), (10, 10, 10))),
+ ("autoCanny", lambda: cv.autoCanny(EMPTY)),
+ ("findLines", lambda: cv.findLines(EMPTY)),
+ ("findCircles", lambda: cv.findCircles(EMPTY)),
+ ("findBlobs", lambda: cv.findBlobs(EMPTY)),
+ ("imshowEx", lambda: cv.imshowEx("w", EMPTY)),
+ ("imshowInline", lambda: cv.imshowInline(EMPTY)),
+ ("imencodeBase64", lambda: cv.imencodeBase64(EMPTY)),
+ ("translate", lambda: cv.translate(EMPTY, 1, 1)),
+ ("cropRotatedRect", lambda: cv.cropRotatedRect(EMPTY, ((5, 5), (4, 4), 0))),
+ ("deskew", lambda: cv.deskew(EMPTY)),
+ ("cropRect", lambda: cv.cropRect(EMPTY, (0, 0, 4, 4))),
+ ("cropCenter", lambda: cv.cropCenter(EMPTY, 4)),
+ ("cropContour", lambda: cv.cropContour(EMPTY, CONTOUR)),
+ ("applyMask", lambda: cv.applyMask(EMPTY, np.zeros((0, 0), np.uint8))),
+ ("kmeansColors", lambda: cv.kmeansColors(EMPTY, 1)),
+ ("meanShiftColors", lambda: cv.meanShiftColors(EMPTY)),
+ ("dbscanColors", lambda: cv.dbscanColors(EMPTY, 1.0)),
+ ("drawClusters", lambda: cv.drawClusters(EMPTY, np.zeros((0, 0), np.int32))),
+ ("matchFeatures", lambda: cv.matchFeatures(EMPTY, IMG)),
+ ("alignImages", lambda: cv.alignImages(IMG, EMPTY)),
+ ("sharpnessScore", lambda: cv.sharpnessScore(EMPTY)),
+ ("imageHash", lambda: cv.imageHash(EMPTY)),
+ ("binarize", lambda: cv.binarize(EMPTY)),
+ ("morphology", lambda: cv.morphology(EMPTY, "open")),
+ ("flattenAlpha", lambda: cv.flattenAlpha(EMPTY)),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -218,28 +327,28 @@ def test_writeVideo_rejects_frames_that_are_not_gray_or_bgr(tmp_path, shape):
cv.writeVideo(tmp_path / "a.avi", [np.zeros(shape, np.uint8)], fps=10)
-# --- urlread size limit ------------------------------------------------------------
+# --- imreadUrl size limit ------------------------------------------------------------
-def test_urlread_maxBytes_accepts_a_file_that_fits(tmp_path, bgr=IMG):
+def test_imreadUrl_maxBytes_accepts_a_file_that_fits(tmp_path, bgr=IMG):
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
- np.testing.assert_array_equal(cv.urlread(path.as_uri(), maxBytes=path.stat().st_size), bgr)
+ np.testing.assert_array_equal(cv.imreadUrl(path.as_uri(), maxBytes=path.stat().st_size), bgr)
-def test_urlread_maxBytes_rejects_a_larger_file(tmp_path, bgr=IMG):
+def test_imreadUrl_maxBytes_rejects_a_larger_file(tmp_path, bgr=IMG):
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
with pytest.raises(ValueError, match="maxBytes"):
- cv.urlread(path.as_uri(), maxBytes=path.stat().st_size - 1)
+ cv.imreadUrl(path.as_uri(), maxBytes=path.stat().st_size - 1)
-def test_urlread_maxBytes_uses_content_length_before_downloading(monkeypatch):
+def test_imreadUrl_maxBytes_uses_content_length_before_downloading(monkeypatch):
import io
import sys
from email.message import Message
- urlread_module = sys.modules["cv2u.imgcodecs.urlread"]
+ urlread_module = sys.modules["cv2u.imgcodecs.url"]
class Response(io.BytesIO):
headers = Message()
@@ -256,4 +365,4 @@ def read(self, n=-1):
monkeypatch.setattr(urlread_module, "urlopen", lambda request, timeout=None: Response())
with pytest.raises(ValueError, match="maxBytes"):
- cv.urlread("https://example.invalid/big.png", maxBytes=1000)
+ cv.imreadUrl("https://example.invalid/big.png", maxBytes=1000)
diff --git a/tests/typing/check_passthrough.py b/tests/typing/check_passthrough.py
index cd6d84b..c7dca11 100644
--- a/tests/typing/check_passthrough.py
+++ b/tests/typing/check_passthrough.py
@@ -23,14 +23,18 @@
cv.rotateEx(gray, "45") # type: ignore[arg-type]
flip_code: int = cv.FLIP_MODE_X
gradient: np.ndarray = cv.makeGradient((2, 2), 0, 255, direction="horizontal")
+gray_gradient: np.ndarray = cv.makeGradient((2, 2), 0, 255, channels=1)
+canvas: np.ndarray = cv.imcolor((4, 4), (1, 2, 3))
cv.makeGradient((2, 2), 0, 255, direction="diagonal") # type: ignore[arg-type]
filled: np.ndarray = cv.imcolorLike(gradient, 0)
maybe_img: np.ndarray | None = cv.imreadEx("사진.png")
written: bool = cv.imwriteEx("out.png", filled)
boxed, scale, (left, top) = cv.letterbox(filled, (640, 640))
+fitted: cv.Letterbox = cv.letterbox(filled, (640, 640))
+fitted_image: np.ndarray = fitted.image
cv.resizeEx(filled, width="640") # type: ignore[arg-type]
side_by_side: np.ndarray = cv.hconcatEx([filled, boxed], gap=4)
-stamped: np.ndarray = cv.overlayImage(filled, boxed, org=(10, 10), opacity=0.5)
+stamped: np.ndarray = cv.overlayImage(filled, boxed, org=(10, 10), alpha=0.5)
info: cv.VideoInfo = cv.videoInfo("clip.mp4")
seconds: float = info.duration
for frame in cv.readFrames("clip.mp4", step=2):
@@ -47,12 +51,14 @@
labeled: np.ndarray = cv.drawLabel(filled, (1, 1, 5, 5), "cat", (0, 255, 0))
cv.drawLabel(filled, (1, 1, 5), "cat", (0, 255, 0)) # type: ignore[arg-type]
tinted: np.ndarray = cv.overlayMask(filled, filled > 0)
-cropped: np.ndarray = cv.cropEx(filled, (-5, -5, 20, 20), fill=0)
+cropped: np.ndarray = cv.cropRect(filled, (-5, -5, 20, 20), fill=0)
red_mask: np.ndarray = cv.inRangeEx(filled, (170, 100, 100), (10, 255, 255))
grid: np.ndarray = cv.montage([filled, cropped], cols=2, cellSize=(64, 64))
equalized: np.ndarray = cv.equalizeHistEx(filled, clahe=True)
sharpened: np.ndarray = cv.unsharpMask(filled, sigma=2.0)
label_map, palette_centers = cv.kmeansColors(filled, 4)
+clusters: cv.Clusters = cv.kmeansColors(filled, 4)
+cluster_maps: np.ndarray = clusters.maps
palette: list[tuple[tuple[int, ...], float]] = cv.dominantColors(filled, k=3)
posterized: np.ndarray = cv.colorQuantize(filled, 8)
auto_map, auto_centers = cv.meanShiftColors(filled)
@@ -63,7 +69,7 @@
contours: list[np.ndarray] = cv.findContoursEx(filled, minArea=10)
solid: np.ndarray = cv.fillHoles(filled, maxHoleArea=100)
clean: np.ndarray = cv.removeSmallObjects(filled, minArea=20)
-found: list[tuple[int, int, int, int, float]] = cv.findTemplate(filled, filled[:4, :4], threshold=0.9)
+found: np.ndarray = cv.findTemplate(filled, filled[:4, :4], threshold=0.9)
trimmed: np.ndarray = cv.cropToContent(filled, tolerance=8)
saved: bool = cv.imwriteEx("out/a.png", filled, makeDirs=True)
orange: tuple[int, ...] = cv.hexToBGR("#ff8800")
@@ -88,8 +94,9 @@
sticker: np.ndarray = cv.cutout(filled, filled[..., 0], feather=2)
thumbnail: np.ndarray | None = cv.readFrameAt("clip.mp4", seconds=1.5)
groups: np.ndarray = cv.clusterPoints([[0, 0], [1, 1]], eps=2.0)
-db_maps, db_labels = cv.DBSCAN(filled, 1.7, minSamples=2)
-cv.DBSCAN(filled, 1.7, min_samples=2) # type: ignore[call-arg]
+db_maps, db_centers = cv.dbscanColors(filled, 1.7, minSamples=2)
+cv.dbscanColors(filled, 1.7, min_samples=2) # type: ignore[call-arg]
+painted: np.ndarray = cv.drawClusters(filled, db_maps)
# Names that are not in the generated stub fall back to Any instead of an error.
cv.some_function_added_in_a_later_opencv_release()
diff --git a/tools/regenerate_goldens.py b/tools/regenerate_goldens.py
index 015a85f..cf2e227 100644
--- a/tools/regenerate_goldens.py
+++ b/tools/regenerate_goldens.py
@@ -41,11 +41,11 @@ def main() -> None:
_write("rotateEx_45.png", cv.rotateEx(rot, 45))
_write("rotateEx_30_scale0.5.png", cv.rotateEx(rot, 30, scale=0.5))
_write("gammaCorrection_2.2.png", cv.gammaCorrection(rot, 2.2))
- _write("DHEdge.png", cv.DHEdge(gray))
+ _write("boldEdges.png", cv.boldEdges(gray))
dbs = cv2.imread(str(DATA / "dbscan_src.png"))
- maps, labels = cv.DBSCAN(dbs, 1.7, 2)
- _write("drawDBSCAN.png", cv.drawDBSCAN(dbs, maps, labels))
+ maps, _ = cv.dbscanColors(dbs, 1.7, 2)
+ _write("drawClusters.png", cv.drawClusters(dbs, maps))
if __name__ == "__main__":
From 8b14c18b4d3a67296504364c4d13c5ef07ae7596 Mon Sep 17 00:00:00 2001
From: 076923 <076923@naver.com>
Date: Sun, 8 Nov 2026 13:53:16 +0900
Subject: [PATCH 4/7] 1.0.0: API reference, design principles and changelog for
the new modules
---
CHANGELOG.md | 57 ++++++++
docs/api.md | 356 ++++++++++++++++++++++++++++++++++++++++++++-
docs/principles.md | 30 +++-
3 files changed, 441 insertions(+), 2 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 30a060d..fabe485 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,63 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.0.0] - 2026-11-08
+
+The first stable release: 162 new APIs (135 -> 297), two new subpackages (`cv2u.calib3d`, `cv2u.dnn`), and a one-time
+clean-up of the existing API (consistent names, signatures and validation). From 1.0 on, the public API follows
+semantic versioning and renames keep a deprecated alias (see [Design principles](docs/principles.md)).
+
+### Added
+
+- `VideoReader`, `VideoWriterEx` and `CameraStream`: context-manager/iterator capture with seeking, a lazily-opened writer that infers codec, size and color mode from the first frame, and a threaded latest-frame camera reader.
+- `FPSCounter`, `frameToTime`, `timeToFrame`, `formatTimestamp`: frame-rate measurement and frame/time conversions.
+- `extractFrames`, `trimVideo`, `concatVideos`, `resizeVideo`, `videoToGif`, `imagesToVideo`: video file editing utilities with Unicode-safe paths and automatic directory creation.
+- `detectScenes`, `sampleFrames`, `videoThumbnail`: scene-cut detection and evenly spaced frame sampling / contact sheets.
+- Data augmentation (`imgproc`): seeded noise, motion blur, vignette, JPEG artifacts, random erase, solarize and posterize (`addNoise`, `motionBlur`, `vignette`, `jpegArtifacts`, `randomErase`, `solarize`, `posterize`).
+- Seeded random transforms that keep detection boxes aligned: `randomCrop`, `randomFlip`, `randomRotate`, `randomScale`, `randomPerspective`; photometric `randomBrightnessContrast`, `randomHSV`, `randomBlur`.
+- Multi-image augmentations `mosaic` (YOLO-style 4-image mosaic with boxes), `mixup` and `cutMix` (both return the mixing weight `lam` for labels).
+- `maskToPolygons`, `polygonsToMask`, `boxesToPolygons`, `polygonsToBoxes`, `polygonArea`, `polygonIoU`, `maskIoU`: polygon annotations and overlap measures (`polygonIoU` rasterizes at a configurable resolution, so it works for concave polygons).
+- `rleEncode`, `rleDecode`: COCO uncompressed RLE (column-major, pycocotools-compatible) without a pycocotools dependency.
+- `boxesToYolo`, `yoloToBoxes`, `readYoloLabels`, `writeYoloLabels`: YOLO normalized rows and `.txt` label files on any path, with `makeDirs`.
+- `labelMapToColor`, `colorToLabelMap`, `instanceMasksToLabelMap`, `labelMapToMasks`, `drawSegmentation`, `drawPolygons`: label maps, instance masks and their visualization with distinct class colors.
+- `flipBoxes`, `flipPoints`, `flipPolygons`: flip annotations together with `cv.flip` (same `flipCode` semantics as `FLIP_MODE_*`).
+- `cv2u.dnn` subpackage (mirrors `cv.dnn`; every `cv2.dnn` name passes through): `loadModel`, `readClassNames`, `preprocessImage`, `inferImage`, `postprocessDetections`, `postprocessClassification`, `softmax`, `sigmoid`, `drawDetections`, and the `PreprocessInfo` / `Detections` named tuples for running detectors and classifiers end to end.
+- `heatmap`, `applyColorMapEx` and `colorBar`: colorize float maps of any size, overlay them on an image and draw a legend strip.
+- `drawArrow` (pixel-sized heads, both ends), `drawRotatedRect`/`drawRotatedBoxes` (from `cv.minAreaRect`), `drawPolygon` (float points, translucent fill), `drawSkeleton` with `COCO_SKELETON`, `drawTrajectory` (fading tracks) and `drawCrosshair`.
+- HUD helpers `drawTextBlock`, `drawFPS`, `drawProgressBar` and `drawLegend` with translucent panels.
+- `compareImages` (side, vertical, split, blend, diff), `labeledMontage` (titled grid) and `blendImages` (weighted average of N images).
+- `imageStats`/`ImageStats`, `isGrayscale`, `isBlank`, `isBlurry`, `brightnessScore`, `contrastScore`, `exposureScore`, `entropy`, `estimateNoise` (Immerkær) and `colorfulness` (Hasler & Süsstrunk): one-call image statistics and quality checks for any gray/BGR/BGRA image and dtype.
+- `mse`, `mae`, `histogramEx` (per-channel `(channels, bins)` histograms), `histogramCompare` (normalized HSV/BGR/gray histograms through `cv.compareHist`), `dominantHue` and `meanColor`.
+- Document and OCR preprocessing (`imgproc`): `removeShadow`, `enhanceDocument`, `sauvolaThreshold`, `niblackThreshold` (integral-image local thresholds, no contrib needed), `removeSpeckles`, `removeLines`.
+- Page layout: `detectTextLines`, `detectTextBlocks`, `removeBorder`, `estimateSkew` (the angle behind `deskew`), `detectPage` and `scanDocument` (detect + `fourPointTransform` + enhance).
+- `cv2u.calib3d` subpackage: `CameraCalibration`, `makeChessboard`, `objectPointsGrid`, `findChessboardEx`, `calibrateCameraEx`, `reprojectionErrors`, `undistortEx`, `saveCalibration`, `loadCalibration` for chessboard camera calibration, undistortion and a JSON calibration file.
+- `stitchImages` (`cv.Stitcher` with exceptions and status names) and `stitchPair` (homography stitch on an enlarged canvas).
+- `imageInfo`, `ImageInfo`, `exifOrientation`: image file header metadata (size, channels, mode, format, file size, EXIF orientation) without decoding.
+- `imreadOriented`, `imreadResized`: read with the EXIF orientation applied for every flag and format, and read-and-resize with `IMREAD_REDUCED_*` fast paths for 1/2, 1/4, 1/8 scales.
+- `imencodeEx`, `imdecodeEx`, `convertImageFormat`: encode to `bytes` with errors raised, decode from any bytes-like object, and convert files between formats (alpha flattened for JPEG, orientation applied, `quality`).
+- Color arithmetic (`imgproc`): `CSS_COLORS`, `lightenColor`, `darkenColor`, `blendColors`, `complementaryColor`, `invertColor`, `colorDistance`, `nearestColor`, `colorName`, `textColorFor`, `randomColors`, `gradientPalette`, `colormapPalette`.
+- Point sets (`core`): `rotatePoints`, `scalePoints`, `translatePoints`, `flipPoints`, `normalizePoints`, `denormalizePoints`, `clipPoints`, `pointsBoundingBox`, `distancePoints`, `nearestPoints`, `orderPoints`, `polygonCentroid`, `angleBetween`, `lineIntersection`, `pointLineDistance`.
+- `Clusters` and `Letterbox` named tuples (see Changed).
+
+### Changed
+- `DBSCAN` is now `dbscanColors(src, eps, minSamples=4)` and returns `Clusters(maps, centers)` like the other clusterers; labels are `0 .. k-1` with noise `-1` (was `(maps, labels)` with noise `0` and clusters from `1`). `clusterPoints` follows the same convention (noise `-1`, `int32` labels).
+- `drawDBSCAN(src, maps, labels)` is now `drawClusters(src, maps)`: returns a new image, accepts gray or BGR input; noise pixels keep their original color.
+- `kmeansColors`, `meanShiftColors`, `peakColors` and `dbscanColors` return a `Clusters(maps, centers)` named tuple, and `letterbox` returns `Letterbox(image, scale, offset)`; tuple unpacking keeps working.
+- Renamed: `DHEdge` -> `boldEdges`, `cropEx` -> `cropRect`, `centerCrop` -> `cropCenter`, `detectBlobs` -> `findBlobs`, `urlread` -> `imreadUrl` (now defaults to `IMREAD_COLOR` like `cv.imread`).
+- Renamed parameters: `matchFeatures(src, reference, ..., mask, referenceMask)` (was `dst`, `dstMask`); `overlayImage(alpha=)` (was `opacity`); `cropContour`, `applyMask` and `flattenAlpha` take `fill=` (was `background`); `expandBoxes(margin=)` (was `pixels`).
+- `imcolor(size, color, channels=3)` and `makeGradient(size, ...)` take `size=(width, height)` like `cv.resize` instead of a NumPy shape; `channels=1` gives a 2-D image.
+- `putTextEx(img, ...)` and `drawContoursEx(img, contours, colors=None, labels=False, thickness=2, fontScale=0.5)` draw in place and return `img` like every other `draw*` function (they returned a BGR copy); grayscale images stay grayscale.
+- `findTemplate` returns a float64 `(N, 5)` array `[x, y, w, h, score]` instead of a list of tuples, so the result feeds `nms` and `drawBoxes` directly.
+- `cropRect` raises `ValueError` when the box lies entirely outside the image instead of returning an empty array.
+- `cropRotatedRect` defaults to `borderMode=cv.BORDER_CONSTANT` like `rotateEx` and `translate`; `rotateEx` has explicit defaults (`INTER_LINEAR`, `BORDER_CONSTANT`, `0`).
+- `drawRoundedRectangle(img, rect, color, thickness=1, radius=8, lineType=...)`: `radius` comes before `lineType`. `drawPoints` default `fontScale` is 0.5.
+- Boolean switches are keyword-only: `padToSize(center=)`, `scaleBoxes(inverse=)`, `equalizeHistEx(clahe=)`, `binarize(invert=)`, `autoContrast(perChannel=)`, `findBlobs(dark=)`, `findContoursEx(sort=)`, `cropContour(transparent=)`, `drawHistogram(log=)`, `imencodeBase64(dataUri=)`, `imreadAll(strict=)`, `imwriteAll(strict=)`.
+- `autoCanny` accepts 16-bit and float images (stretched to 8 bits) instead of raising; `findLines` does the same. `nms` rejects `iouThreshold > 1`. `minArea` is a `float` everywhere.
+- Validation is now uniform: every function rejects empty images, and every numeric parameter rejects NaN/infinity and out-of-range values, with a `ValueError` naming the argument (about 50 functions gained checks). Every public function has complete `Args`/`Returns`/`Raises` docstrings.
+
+### Removed
+- `DBSCAN`, `drawDBSCAN`, `DHEdge`, `cropEx`, `centerCrop`, `detectBlobs` and `urlread` (renamed above). 1.0.0 is a one-time reset without deprecated aliases; from 1.0 on, renames keep a deprecated alias for at least one minor release.
+
## [0.4.0] - 2026-11-07
3 new APIs (132 -> 135), and the hot paths measured.
diff --git a/docs/api.md b/docs/api.md
index 5ee1b19..2ed75af 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1,5 +1,5 @@
---
-description: "API reference for cv2u: imreadEx, imwriteEx, toPillow, imencodeBase64, readFrames, writeVideo, imshowInline, resizeEx, letterbox, drawLabel, overlayMask, cropRect, montage, equalizeHistEx and more."
+description: "API reference for cv2u: VideoReader, augmentation, YOLO and COCO annotations, dnn inference, calibration, document scanning, imreadEx, imwriteEx, toPillow, imencodeBase64, readFrames, writeVideo, imshowInline, resizeEx, letterbox, drawLabel, overlayMask, cropRect, montage, equalizeHistEx and more."
---
# API reference
@@ -105,6 +105,82 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.core.cluster.clusterPoints
+### Point sets
+
+::: cv2u.core.points.rotatePoints
+
+::: cv2u.core.points.scalePoints
+
+::: cv2u.core.points.translatePoints
+
+::: cv2u.core.points.flipPoints
+
+::: cv2u.core.points.normalizePoints
+
+::: cv2u.core.points.denormalizePoints
+
+::: cv2u.core.points.clipPoints
+
+::: cv2u.core.points.pointsBoundingBox
+
+::: cv2u.core.points.distancePoints
+
+::: cv2u.core.points.nearestPoints
+
+::: cv2u.core.points.orderPoints
+
+::: cv2u.core.points.polygonCentroid
+
+::: cv2u.core.points.angleBetween
+
+::: cv2u.core.points.lineIntersection
+
+::: cv2u.core.points.pointLineDistance
+
+### Annotation formats
+
+::: cv2u.core.annotations.maskToPolygons
+
+::: cv2u.core.annotations.polygonsToMask
+
+::: cv2u.core.annotations.boxesToPolygons
+
+::: cv2u.core.annotations.polygonsToBoxes
+
+::: cv2u.core.annotations.polygonArea
+
+::: cv2u.core.annotations.polygonIoU
+
+::: cv2u.core.annotations.maskIoU
+
+::: cv2u.core.annotations.rleEncode
+
+::: cv2u.core.annotations.rleDecode
+
+::: cv2u.core.annotations.boxesToYolo
+
+::: cv2u.core.annotations.yoloToBoxes
+
+::: cv2u.core.annotations.readYoloLabels
+
+::: cv2u.core.annotations.writeYoloLabels
+
+::: cv2u.core.annotations.labelMapToColor
+
+::: cv2u.core.annotations.colorToLabelMap
+
+::: cv2u.core.annotations.instanceMasksToLabelMap
+
+::: cv2u.core.annotations.labelMapToMasks
+
+::: cv2u.core.annotations.drawPolygons
+
+::: cv2u.core.annotations.drawSegmentation
+
+::: cv2u.core.annotations.flipBoxes
+
+::: cv2u.core.annotations.flipPolygons
+
## imgcodecs
::: cv2u.imgcodecs.files.imreadEx
@@ -127,6 +203,24 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.imgcodecs.convert.imdecodeBase64
+### Image file metadata
+
+::: cv2u.imgcodecs.meta.ImageInfo
+
+::: cv2u.imgcodecs.meta.imageInfo
+
+::: cv2u.imgcodecs.meta.exifOrientation
+
+::: cv2u.imgcodecs.meta.imreadOriented
+
+::: cv2u.imgcodecs.meta.imreadResized
+
+::: cv2u.imgcodecs.meta.imencodeEx
+
+::: cv2u.imgcodecs.meta.imdecodeEx
+
+::: cv2u.imgcodecs.meta.convertImageFormat
+
## imgproc
### Color conversion
@@ -279,6 +373,178 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.imgproc.puttext.putTextEx
+### Image statistics and quality checks
+
+::: cv2u.imgproc.stats.ImageStats
+
+::: cv2u.imgproc.stats.imageStats
+
+::: cv2u.imgproc.stats.isGrayscale
+
+::: cv2u.imgproc.stats.isBlank
+
+::: cv2u.imgproc.stats.isBlurry
+
+::: cv2u.imgproc.stats.brightnessScore
+
+::: cv2u.imgproc.stats.contrastScore
+
+::: cv2u.imgproc.stats.colorfulness
+
+::: cv2u.imgproc.stats.exposureScore
+
+::: cv2u.imgproc.stats.entropy
+
+::: cv2u.imgproc.stats.estimateNoise
+
+::: cv2u.imgproc.stats.mse
+
+::: cv2u.imgproc.stats.mae
+
+::: cv2u.imgproc.stats.histogramEx
+
+::: cv2u.imgproc.stats.histogramCompare
+
+::: cv2u.imgproc.stats.dominantHue
+
+::: cv2u.imgproc.stats.meanColor
+
+### Color arithmetic
+
+::: cv2u.imgproc.palette.CSS_COLORS
+
+::: cv2u.imgproc.palette.lightenColor
+
+::: cv2u.imgproc.palette.darkenColor
+
+::: cv2u.imgproc.palette.blendColors
+
+::: cv2u.imgproc.palette.complementaryColor
+
+::: cv2u.imgproc.palette.invertColor
+
+::: cv2u.imgproc.palette.colorDistance
+
+::: cv2u.imgproc.palette.nearestColor
+
+::: cv2u.imgproc.palette.colorName
+
+::: cv2u.imgproc.palette.textColorFor
+
+::: cv2u.imgproc.palette.randomColors
+
+::: cv2u.imgproc.palette.gradientPalette
+
+::: cv2u.imgproc.palette.colormapPalette
+
+### Data augmentation
+
+::: cv2u.imgproc.augment.addNoise
+
+::: cv2u.imgproc.augment.motionBlur
+
+::: cv2u.imgproc.augment.vignette
+
+::: cv2u.imgproc.augment.jpegArtifacts
+
+::: cv2u.imgproc.augment.randomErase
+
+::: cv2u.imgproc.augment.solarize
+
+::: cv2u.imgproc.augment.posterize
+
+::: cv2u.imgproc.augment.randomCrop
+
+::: cv2u.imgproc.augment.randomFlip
+
+::: cv2u.imgproc.augment.randomRotate
+
+::: cv2u.imgproc.augment.randomScale
+
+::: cv2u.imgproc.augment.randomPerspective
+
+::: cv2u.imgproc.augment.randomBrightnessContrast
+
+::: cv2u.imgproc.augment.randomHSV
+
+::: cv2u.imgproc.augment.randomBlur
+
+::: cv2u.imgproc.augment.mosaic
+
+::: cv2u.imgproc.augment.mixup
+
+::: cv2u.imgproc.augment.cutMix
+
+### Documents and OCR
+
+::: cv2u.imgproc.document.removeShadow
+
+::: cv2u.imgproc.document.enhanceDocument
+
+::: cv2u.imgproc.document.sauvolaThreshold
+
+::: cv2u.imgproc.document.niblackThreshold
+
+::: cv2u.imgproc.document.removeSpeckles
+
+::: cv2u.imgproc.document.removeLines
+
+::: cv2u.imgproc.document.detectTextLines
+
+::: cv2u.imgproc.document.detectTextBlocks
+
+::: cv2u.imgproc.document.removeBorder
+
+::: cv2u.imgproc.document.estimateSkew
+
+::: cv2u.imgproc.document.detectPage
+
+::: cv2u.imgproc.document.scanDocument
+
+### Stitching
+
+::: cv2u.imgproc.stitch.stitchImages
+
+::: cv2u.imgproc.stitch.stitchPair
+
+### Visualization
+
+::: cv2u.imgproc.visualize.applyColorMapEx
+
+::: cv2u.imgproc.visualize.heatmap
+
+::: cv2u.imgproc.visualize.colorBar
+
+::: cv2u.imgproc.visualize.drawArrow
+
+::: cv2u.imgproc.visualize.drawRotatedRect
+
+::: cv2u.imgproc.visualize.drawRotatedBoxes
+
+::: cv2u.imgproc.visualize.drawPolygon
+
+::: cv2u.imgproc.visualize.drawSkeleton
+
+::: cv2u.imgproc.visualize.COCO_SKELETON
+
+::: cv2u.imgproc.visualize.drawTrajectory
+
+::: cv2u.imgproc.visualize.drawCrosshair
+
+::: cv2u.imgproc.visualize.drawTextBlock
+
+::: cv2u.imgproc.visualize.drawFPS
+
+::: cv2u.imgproc.visualize.drawProgressBar
+
+::: cv2u.imgproc.visualize.drawLegend
+
+::: cv2u.imgproc.visualize.compareImages
+
+::: cv2u.imgproc.visualize.labeledMontage
+
+::: cv2u.imgproc.visualize.blendImages
+
## videoio
::: cv2u.videoio.video.readFrames
@@ -293,12 +559,100 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
options:
members: [width, height, fps, frameCount, duration]
+### Readers and writers
+
+::: cv2u.videoio.reader.VideoReader
+
+::: cv2u.videoio.reader.VideoWriterEx
+
+::: cv2u.videoio.reader.CameraStream
+
+::: cv2u.videoio.reader.FPSCounter
+
+::: cv2u.videoio.reader.frameToTime
+
+::: cv2u.videoio.reader.timeToFrame
+
+::: cv2u.videoio.reader.formatTimestamp
+
+### Video files
+
+::: cv2u.videoio.edit.extractFrames
+
+::: cv2u.videoio.edit.trimVideo
+
+::: cv2u.videoio.edit.concatVideos
+
+::: cv2u.videoio.edit.resizeVideo
+
+::: cv2u.videoio.edit.videoToGif
+
+::: cv2u.videoio.edit.imagesToVideo
+
+::: cv2u.videoio.edit.detectScenes
+
+::: cv2u.videoio.edit.sampleFrames
+
+::: cv2u.videoio.edit.videoThumbnail
+
## highgui
::: cv2u.highgui.display.imshowInline
::: cv2u.highgui.display.imshowEx
+## calib3d
+
+Camera calibration helpers; the OpenCV calib3d functions (`cv.calibrateCamera`, `cv.undistort`, ...) stay available as they are.
+
+### Camera calibration
+
+::: cv2u.calib3d.calibrate.CameraCalibration
+
+::: cv2u.calib3d.calibrate.makeChessboard
+
+::: cv2u.calib3d.calibrate.objectPointsGrid
+
+::: cv2u.calib3d.calibrate.findChessboardEx
+
+::: cv2u.calib3d.calibrate.calibrateCameraEx
+
+::: cv2u.calib3d.calibrate.reprojectionErrors
+
+::: cv2u.calib3d.calibrate.undistortEx
+
+::: cv2u.calib3d.calibrate.saveCalibration
+
+::: cv2u.calib3d.calibrate.loadCalibration
+
+## dnn
+
+`cv.dnn` is the `cv2u.dnn` package: it adds the helpers below and passes every `cv2.dnn` name (`cv.dnn.readNet`, `cv.dnn.NMSBoxes`, ...) through.
+
+### Inference
+
+::: cv2u.dnn.inference.PreprocessInfo
+
+::: cv2u.dnn.inference.Detections
+
+::: cv2u.dnn.inference.loadModel
+
+::: cv2u.dnn.inference.readClassNames
+
+::: cv2u.dnn.inference.preprocessImage
+
+::: cv2u.dnn.inference.inferImage
+
+::: cv2u.dnn.inference.postprocessDetections
+
+::: cv2u.dnn.inference.postprocessClassification
+
+::: cv2u.dnn.inference.softmax
+
+::: cv2u.dnn.inference.sigmoid
+
+::: cv2u.dnn.inference.drawDetections
+
## flag
Named constants for magic numbers that OpenCV functions take without a constant of their own.
diff --git a/docs/principles.md b/docs/principles.md
index a7156b9..cbb1dfa 100644
--- a/docs/principles.md
+++ b/docs/principles.md
@@ -71,6 +71,33 @@ Never re-implement something OpenCV already does well.
| `dominantColors`, `colorQuantize`, `kmeansColors` | `cv.kmeans` needs reshaping, float conversion and criteria, and its results change from run to run (global RNG). |
| `peakColors` | Automatic color clustering usually needs scikit-learn, samples the pixels and is slow; cv2u's own histogram-peak method needs neither. |
| `meanShiftColors`, `dbscanColors`, `drawClusters`, `clusterPoints` | OpenCV has no clustering that finds the number of groups by itself, for colors or for points. |
+| `VideoReader`, `VideoWriterEx`, `CameraStream` | `cv.VideoCapture`/`cv.VideoWriter` need `isOpened()` checks, `CAP_PROP_*` getters, fourcc/size/`isColor` up front, manual `release()`, and buffer live streams so a slow consumer reads stale frames. |
+| `extractFrames`, `trimVideo`, `concatVideos`, `resizeVideo`, `videoToGif`, `imagesToVideo` | Every "ffmpeg-lite" task (dump frames, cut, join, resize, GIF, time-lapse) is the same read/write loop; OpenCV cannot write GIFs at all. |
+| `detectScenes`, `sampleFrames`, `videoThumbnail`, `FPSCounter`, `formatTimestamp` | Scene cuts, preview sheets, FPS overlays and `HH:MM:SS.mmm` stamps are rewritten in every video script. |
+| `addNoise`, `motionBlur`, `vignette`, `jpegArtifacts`, `solarize`, `posterize` | Classic photo degradations for augmentation have no OpenCV function (`cv.randn` needs a preallocated array; directional blur, vignetting, solarize and posterize are rewritten in every project). |
+| `randomCrop`, `randomFlip`, `randomRotate`, `randomScale`, `randomPerspective` | `cv.flip`/`cv.warpAffine` never touch the detection boxes; keeping labels aligned with a random geometric transform is bookkeeping everyone rewrites. |
+| `mosaic`, `mixup`, `cutMix`, `randomErase` | The standard detector/classifier mixing augmentations otherwise require albumentations or a framework-specific loader. |
+| `maskToPolygons`, `polygonsToMask`, `rleEncode`, `rleDecode` | Datasets store masks as COCO polygons or RLE; `cv.findContours`/`cv.fillPoly` need `int32 (N, 1, 2)` arrays, keep one-pixel specks, and OpenCV has no run-length encoding at all. |
+| `boxesToYolo`, `yoloToBoxes`, `readYoloLabels`, `writeYoloLabels`, `flipBoxes`, `flipPolygons` | Normalized `class cx cy w h` label files and keeping annotations aligned with `cv.flip` are the same arithmetic in every training script. |
+| `polygonIoU`, `polygonArea`, `maskIoU`, `labelMapToColor`, `colorToLabelMap`, `drawSegmentation` | `cv.intersectConvexConvex` only handles convex shapes, `cv.contourArea` rounds to integers, and coloring / recovering a class-id map has no OpenCV function. |
+| `preprocessImage`, `postprocessDetections` | `cv.dnn.blobFromImage` stretches the image and forgets the geometry, and nothing in OpenCV decodes YOLO-style outputs; cv2u letterboxes, keeps the mapping and returns boxes on the original image after per-class NMS. |
+| `loadModel`, `readClassNames` | `cv.dnn.readNet` cannot open non-ASCII paths on Windows and reports a missing file as a C++ assertion; cv2u reads ONNX/TFLite/TF models through Python and raises `FileNotFoundError`. |
+| `inferImage`, `drawDetections` | `Net.forward()` returns only the first output and OpenCV has no labeled-detection drawing; cv2u returns every output layer and draws boxes with class names and scores. |
+| `heatmap`, `applyColorMapEx`, `colorBar` | `cv.applyColorMap` only takes an 8-bit map of the image size; overlaying a float attention/saliency map means normalize, convert, resize and `addWeighted` every time, and there is no legend strip. |
+| `drawArrow`, `drawRotatedRect`, `drawPolygon`, `drawSkeleton`, `drawTrajectory`, `drawCrosshair` | `cv.arrowedLine` sizes the head relative to the arrow length, OpenCV cannot draw its own `RotatedRect`, `polylines`/`fillPoly` need `int32 (N, 1, 2)` and draw opaque only, and poses, tracks and crosshairs have no drawing function. |
+| `drawTextBlock`, `drawFPS`, `drawProgressBar`, `drawLegend`, `compareImages`, `labeledMontage`, `blendImages` | `cv.putText` writes one line with no background; HUD panels, before/after views (split, blend, diff) and titled grids are the same boilerplate in every demo; `cv.addWeighted` blends exactly two images. |
+| `imageStats`, `isBlank`, `isBlurry`, `estimateNoise` | Dataset triage (flat frames, out-of-focus shots, noise level, entropy) needs a handful of numpy formulas per image; `cv.meanStdDev`/`cv.minMaxLoc` only cover parts and `cv.minMaxLoc` rejects color images. |
+| `histogramEx`, `histogramCompare` | `cv.calcHist` takes lists of images, channels and ranges per dtype and returns a `(bins, 1)` column per call; comparing two images needs the same setup twice plus normalization. |
+| `mse`, `mae`, `colorfulness`, `dominantHue` | Only `cv.PSNR` exists for error metrics (log scale, overflow-prone on `uint8` by hand), and there is no colorfulness or dominant-hue measure. |
+| `sauvolaThreshold`, `niblackThreshold` | Local thresholds for OCR only exist in the `ximgproc` contrib module (`niBlackThreshold`), which `opencv-python` does not ship; here they are built from `cv.integral2`. |
+| `removeShadow`, `removeLines`, `removeSpeckles`, `enhanceDocument` | Cleaning a photographed page (shadows, table rules, dust) is a well-known chain of dilate/medianBlur/morphologyEx/inpaint calls that every OCR project rewrites. |
+| `detectPage`, `scanDocument`, `detectTextLines`, `detectTextBlocks`, `estimateSkew`, `removeBorder` | There is no function from "photo of a document" to an upright page, its text lines or its skew angle; only the primitives (`Canny`, `approxPolyDP`, `connectedComponentsWithStats`). |
+| `findChessboardEx`, `calibrateCameraEx`, `undistortEx` | The calibration tutorial is a page of boilerplate: object-point grids, `(found, corners)` tuples with `(N,1,2)` shapes, a separate `cornerSubPix` on a gray copy, and `undistort` that leaves black borders unless you also call `getOptimalNewCameraMatrix` and crop the ROI. |
+| `saveCalibration`, `loadCalibration` | `cv.FileStorage` writes YAML/XML and cannot open non-ASCII paths on Windows; a JSON file works everywhere. |
+| `stitchImages`, `stitchPair` | `cv.Stitcher.stitch` returns a bare integer status and `None` instead of raising, and the bare `warpPerspective` stitch cuts off whatever lands outside the first image. |
+| `imageInfo`, `imreadOriented`, `imreadResized` | `cv.imread` must decode the whole file to tell its size, applies the EXIF orientation only for `IMREAD_COLOR`/`IMREAD_GRAYSCALE` (not for `IMREAD_UNCHANGED` or `IMREAD_REDUCED_*`), and reduced-size decoding is a flag few know. |
+| `imencodeEx`, `imdecodeEx`, `convertImageFormat` | `cv.imencode` returns `(ok, array)` instead of `bytes`, `cv.imdecode` needs `np.frombuffer` first, and converting a file to JPEG silently drops the alpha channel. |
+| `lightenColor`, `colorName`, `textColorFor`, `rotatePoints`, `distancePoints`, `lineIntersection` | OpenCV converts whole images between color spaces but has nothing for one color, and transforms points only through matrices: no distance matrix, corner ordering, flip or line intersection. |
| `FLIP_MODE_*`, `DDEPTH_SAME`, `ALL_CONTOURS`, `REDUCE_TO_*`, `WAIT_FOREVER`, `KEY_*` | Parameters such as `flipCode`, `ddepth`, `contourIdx`, `dim` and `cv.waitKey` take magic numbers with no OpenCV constant (OpenCV's own constants like `cv.FILLED` are used as they are). |
## 2. Look like OpenCV
@@ -78,7 +105,8 @@ Never re-implement something OpenCV already does well.
An extension should feel like it was always part of OpenCV.
- **Modules** mirror OpenCV's: `core`, `imgcodecs` (reading and writing images), `imgproc` (image processing),
- `videoio` (video files and cameras) and `highgui` (showing images).
+ `videoio` (video files and cameras), `highgui` (showing images), `calib3d` (camera calibration) and `dnn`
+ (inference; `cv.dnn` is the `cv2u.dnn` package, which passes every OpenCV name through).
An extension goes where the OpenCV function it extends lives (`resizeEx` in `imgproc` like `cv.resize`).
- **Names** use camelCase like OpenCV. An extended version of an existing OpenCV function gets the `Ex` suffix
(`rotateEx` for `cv.rotate`, `putTextEx` for `cv.putText`). Constants use `UPPER_CASE`.
From be861435014a09a40d268d55abae697fe6e4f804 Mon Sep 17 00:00:00 2001
From: 076923 <076923@naver.com>
Date: Sun, 8 Nov 2026 13:58:57 +0900
Subject: [PATCH 5/7] 1.0.0: README, docs index and package metadata
---
README.md | 169 ++++++++++++++++++++++++++++++++++++++++++++++++-
docs/index.md | 78 ++++++++++++++++++++++-
pyproject.toml | 34 +++++++++-
3 files changed, 276 insertions(+), 5 deletions(-)
diff --git a/README.md b/README.md
index 56c4d8e..5be9762 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,10 @@
# Python OpenCV Utilities
Python OpenCV Utilities provides useful extensions for [OpenCV](https://opencv.org/)
-and can be used as a **drop-in replacement for `cv2`**.
+and can be used as a **drop-in replacement for `cv2`**. It covers the everyday gaps (Unicode paths, aspect-ratio
+resize, crop-free rotation, Unicode text) and whole workflows: video reading and editing, data augmentation,
+annotation formats (COCO polygons, RLE, YOLO), running ONNX models with `cv.dnn`, camera calibration, document
+scanning and OCR preprocessing, image statistics and visualization.
```python
import cv2u as cv # instead of: import cv2 as cv
@@ -139,6 +142,81 @@ lines = cv.findLines(img, minLength=100) # (N, 4) segments, longest first
aligned, M = cv.alignImages(cv.imread("scan.png"), cv.imread("template.png")) # feature match + RANSAC + warp
```
+### Training data
+
+```python
+import cv2u as cv
+
+img = cv.imread("train/0001.jpg")
+size = (img.shape[1], img.shape[0])
+boxes, classIds = cv.readYoloLabels("train/0001.txt", size) # normalized rows -> pixel (x, y, w, h)
+img, boxes = cv.randomFlip(img, horizontal=0.5, boxes=boxes, seed=1) # the boxes follow the image
+img, boxes = cv.randomRotate(img, maxAngle=10, boxes=boxes, seed=1)
+img = cv.randomHSV(cv.addNoise(img, "gaussian", seed=1), hue=10, seed=1)
+cv.writeYoloLabels("aug/0001.txt", boxes, classIds, size, makeDirs=True)
+cv.imwriteEx("aug/0001.jpg", cv.jpegArtifacts(img, quality=40))
+
+tiles = cv.imreadAll(["train/0001.jpg", "train/0002.jpg", "train/0003.jpg", "train/0004.jpg"])
+labels = [cv.readYoloLabels(f"train/{i:04d}.txt", (t.shape[1], t.shape[0]))[0] for i, t in enumerate(tiles, 1)]
+big, bigBoxes = cv.mosaic(tiles, (640, 640), boxes=labels, seed=1) # YOLO-style 4-image mosaic
+polygons = cv.maskToPolygons(cv.binarize(img, "otsu", invert=True)) # COCO polygons from a mask
+rle = cv.rleEncode(cv.polygonsToMask(polygons, size)) # and uncompressed RLE, no pycocotools needed
+```
+
+### Running a model
+
+```python
+import cv2u as cv
+
+net = cv.dnn.loadModel("C:/모델/yolov8n.onnx") # Unicode path; FileNotFoundError instead of a C++ assertion
+names = cv.dnn.readClassNames("coco.names")
+img = cv.imread("street.jpg")
+blob, info = cv.dnn.preprocessImage(img, (640, 640)) # letterbox + blob; info remembers the geometry
+output = cv.dnn.inferImage(net, blob)[0] # every output layer, not just the first
+dets = cv.dnn.postprocessDetections(
+ output, info, scoreThreshold=0.3
+) # YOLO rows -> Detections(boxes, scores, classIds)
+cv.imwrite("result.png", cv.dnn.drawDetections(img, dets, names)) # boxes on the original image
+```
+
+Everything else in `cv.dnn` (`cv.dnn.readNet`, `cv.dnn.blobFromImage`, `cv.dnn.NMSBoxes`, ...) is passed through from OpenCV.
+
+### Video tools
+
+```python
+import cv2u as cv
+
+fps = cv.FPSCounter()
+with cv.VideoReader("input.mp4") as video, cv.VideoWriterEx("out.mp4", fps=video.fps) as writer:
+ video.seekTime(5.0) # start at 00:05
+ for frame in video:
+ fps.tick()
+ writer.write(cv.drawFPS(cv.autoCanny(frame), fps.fps)) # codec, size and color mode from the first frame
+
+cuts = cv.detectScenes("input.mp4", threshold=30) # frame indices where a new shot starts
+print([cv.formatTimestamp(cv.frameToTime(i, video.fps)) for i in cuts]) # "00:00:12.400", ...
+cv.extractFrames("input.mp4", "frames/", step=30, ext=".png") # one file every 30 frames
+cv.videoToGif("input.mp4", "preview.gif", fps=10, size=(320, 180), maxFrames=50)
+cv.imwrite("sheet.jpg", cv.videoThumbnail("input.mp4", count=6, cols=3)) # contact sheet
+```
+
+### Documents and quality
+
+```python
+import cv2u as cv
+
+photo = cv.imread("receipt.jpg")
+page = cv.scanDocument(photo) # detect the page, warp it upright, clean the background
+mask = cv.sauvolaThreshold(page, invert=True) # local threshold for OCR, no contrib module needed
+for x, y, w, h in cv.detectTextLines(page): # one box per text line, top to bottom
+ cv.drawDashedRectangle(page, (x, y, w, h), (0, 160, 255))
+
+stats = cv.imageStats(photo) # ImageStats(width, height, channels, dtype, mean, std, ..., sharpness, entropy, isGray)
+if cv.isBlurry(photo) or cv.isBlank(photo):
+ print("retake:", stats.sharpness, stats.contrast)
+cv.imwrite("compare.png", cv.compareImages(photo, page, mode="side", labels=["photo", "scan"]))
+```
+
### rotateEx
Rotates an image without cropping its corners. The canvas grows to fit the result.
@@ -296,6 +374,22 @@ Full reference with parameters and exceptions:
```
+### Training data
+
+```python
+import cv2u as cv
+
+img = cv.imread("train/0001.jpg")
+size = (img.shape[1], img.shape[0])
+boxes, classIds = cv.readYoloLabels("train/0001.txt", size) # normalized rows -> pixel (x, y, w, h)
+img, boxes = cv.randomFlip(img, horizontal=0.5, boxes=boxes, seed=1) # the boxes follow the image
+img, boxes = cv.randomRotate(img, maxAngle=10, boxes=boxes, seed=1)
+img = cv.randomHSV(cv.addNoise(img, "gaussian", seed=1), hue=10, seed=1)
+cv.writeYoloLabels("aug/0001.txt", boxes, classIds, size, makeDirs=True)
+cv.imwriteEx("aug/0001.jpg", cv.jpegArtifacts(img, quality=40))
+
+tiles = cv.imreadAll(["train/0001.jpg", "train/0002.jpg", "train/0003.jpg", "train/0004.jpg"])
+labels = [cv.readYoloLabels(f"train/{i:04d}.txt", (t.shape[1], t.shape[0]))[0] for i, t in enumerate(tiles, 1)]
+big, bigBoxes = cv.mosaic(tiles, (640, 640), boxes=labels, seed=1) # YOLO-style 4-image mosaic
+polygons = cv.maskToPolygons(cv.binarize(img, "otsu", invert=True)) # COCO polygons from a mask
+rle = cv.rleEncode(cv.polygonsToMask(polygons, size)) # and uncompressed RLE, no pycocotools needed
+```
+
+### Running a model
+
+```python
+import cv2u as cv
+
+net = cv.dnn.loadModel("C:/모델/yolov8n.onnx") # Unicode path; FileNotFoundError instead of a C++ assertion
+names = cv.dnn.readClassNames("coco.names")
+img = cv.imread("street.jpg")
+blob, info = cv.dnn.preprocessImage(img, (640, 640)) # letterbox + blob; info remembers the geometry
+output = cv.dnn.inferImage(net, blob)[0] # every output layer, not just the first
+dets = cv.dnn.postprocessDetections(
+ output, info, scoreThreshold=0.3
+) # YOLO rows -> Detections(boxes, scores, classIds)
+cv.imwrite("result.png", cv.dnn.drawDetections(img, dets, names)) # boxes on the original image
+```
+
+Everything else in `cv.dnn` (`cv.dnn.readNet`, `cv.dnn.blobFromImage`, `cv.dnn.NMSBoxes`, ...) is passed through from OpenCV.
+
+### Video tools
+
+```python
+import cv2u as cv
+
+fps = cv.FPSCounter()
+with cv.VideoReader("input.mp4") as video, cv.VideoWriterEx("out.mp4", fps=video.fps) as writer:
+ video.seekTime(5.0) # start at 00:05
+ for frame in video:
+ fps.tick()
+ writer.write(cv.drawFPS(cv.autoCanny(frame), fps.fps)) # codec, size and color mode from the first frame
+
+cuts = cv.detectScenes("input.mp4", threshold=30) # frame indices where a new shot starts
+print([cv.formatTimestamp(cv.frameToTime(i, video.fps)) for i in cuts]) # "00:00:12.400", ...
+cv.extractFrames("input.mp4", "frames/", step=30, ext=".png") # one file every 30 frames
+cv.videoToGif("input.mp4", "preview.gif", fps=10, size=(320, 180), maxFrames=50)
+cv.imwrite("sheet.jpg", cv.videoThumbnail("input.mp4", count=6, cols=3)) # contact sheet
+```
+
+### Documents and quality
+
+```python
+import cv2u as cv
+
+photo = cv.imread("receipt.jpg")
+page = cv.scanDocument(photo) # detect the page, warp it upright, clean the background
+mask = cv.sauvolaThreshold(page, invert=True) # local threshold for OCR, no contrib module needed
+for x, y, w, h in cv.detectTextLines(page): # one box per text line, top to bottom
+ cv.drawDashedRectangle(page, (x, y, w, h), (0, 160, 255))
+
+stats = cv.imageStats(photo) # ImageStats(width, height, channels, dtype, mean, std, ..., sharpness, entropy, isGray)
+if cv.isBlurry(photo) or cv.isBlank(photo):
+ print("retake:", stats.sharpness, stats.contrast)
+cv.imwrite("compare.png", cv.compareImages(photo, page, mode="side", labels=["photo", "scan"]))
+```
+
### rotateEx
Rotates an image without cropping its corners. The canvas grows to fit the result.
diff --git a/pyproject.toml b/pyproject.toml
index 663e688..612071f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
[project]
name = "python-opencv-utils"
dynamic = ["version"]
-description = "Drop-in cv2 replacement (import cv2u as cv) with extra OpenCV utilities: crop-free rotation, DBSCAN color clustering, Unicode text rendering, gradients and more"
+description = "Drop-in cv2 replacement (import cv2u as cv) with extra OpenCV utilities: video editing, data augmentation, COCO/YOLO annotations, ONNX inference, camera calibration, document scanning, image statistics, visualization, color clustering, Unicode paths and text, and more"
readme = "README.md"
license = "Apache-2.0"
license-files = ["LICENSE", "NOTICE"]
@@ -90,6 +90,34 @@ keywords = [
"histogram",
"skeletonization",
"background-removal",
+ "video-editing",
+ "video-writer",
+ "scene-detection",
+ "gif",
+ "data-augmentation",
+ "augmentation",
+ "mixup",
+ "cutmix",
+ "yolo",
+ "coco",
+ "rle",
+ "dnn",
+ "onnx",
+ "inference",
+ "object-detection",
+ "camera-calibration",
+ "undistort",
+ "stitching",
+ "panorama",
+ "ocr",
+ "deskew",
+ "heatmap",
+ "visualization",
+ "exif",
+ "image-metadata",
+ "image-statistics",
+ "css-colors",
+ "color-names",
"numpy",
"pillow",
"utilities",
@@ -97,7 +125,7 @@ keywords = [
"type-hints",
]
classifiers = [
- "Development Status :: 4 - Beta",
+ "Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
@@ -133,7 +161,7 @@ opencv = ["opencv-python>=4.10.0.84"]
headless = ["opencv-python-headless>=4.10.0.84"]
contrib = ["opencv-contrib-python>=4.10.0.84"]
contrib-headless = ["opencv-contrib-python-headless>=4.10.0.84"]
-# Needed only for meanShiftColors, DBSCAN and clusterPoints.
+# Needed only for meanShiftColors, dbscanColors and clusterPoints.
cluster = ["scikit-learn>=1.4.2"]
# Labels follow https://packaging.python.org/en/latest/specifications/well-known-project-urls/
From 4086268a98165720f5c11193fccbdac53cd54fe7 Mon Sep 17 00:00:00 2001
From: 076923 <076923@naver.com>
Date: Sun, 8 Nov 2026 14:05:52 +0900
Subject: [PATCH 6/7] Tests: skip WebP orientation cases without Pillow WebP
support; tolerate sub-pixel warp differences in stitchPair
---
tests/test_meta.py | 4 +++-
tests/test_stitch.py | 6 +++---
2 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/tests/test_meta.py b/tests/test_meta.py
index 4f7631f..24fbc32 100644
--- a/tests/test_meta.py
+++ b/tests/test_meta.py
@@ -1,7 +1,7 @@
import cv2
import numpy as np
import pytest
-from PIL import Image, ImageOps
+from PIL import Image, ImageOps, features
from cv2u.imgcodecs.files import imreadEx
from cv2u.imgcodecs.meta import (
@@ -79,6 +79,8 @@ def test_image_info_errors(tmp_path):
@pytest.mark.parametrize("orientation", range(1, 9))
@pytest.mark.parametrize("ext", [".jpg", ".png", ".webp"])
def test_imread_oriented_matches_pillow(tmp_path, orientation, ext):
+ if ext == ".webp" and not features.check("webp"):
+ pytest.skip("Pillow was built without WebP support")
img = _image()
path = _save(tmp_path / f"o{ext}", img, orientation=orientation, quality=100)
expected = ImageOps.exif_transpose(Image.open(path))
diff --git a/tests/test_stitch.py b/tests/test_stitch.py
index d8a4bb8..52045f2 100644
--- a/tests/test_stitch.py
+++ b/tests/test_stitch.py
@@ -36,10 +36,10 @@ def test_stitch_pair(halves: tuple[np.ndarray, np.ndarray, np.ndarray]) -> None:
out = stitchPair(left, right)
assert out.dtype == np.uint8 and out.ndim == 3
assert abs(out.shape[1] - WIDTH) <= 6 and abs(out.shape[0] - HEIGHT) <= 6
- # the left image is pasted unchanged somewhere on the canvas, and the whole scene is reproduced around it
+ # the left image is pasted (almost) unchanged somewhere on the canvas, and the whole scene is reproduced around it
scores = cv2.matchTemplate(out, left, cv2.TM_SQDIFF)
- _, _, (x, y), _ = cv2.minMaxLoc(scores)
- assert scores[y, x] == 0
+ best, _, (x, y), _ = cv2.minMaxLoc(scores)
+ assert best / left.size < 1.0 # mean squared difference per value; warping may touch a few border pixels
region = out[y : y + HEIGHT, x : x + WIDTH]
assert region.shape == scene.shape and cv2.absdiff(region, scene).mean() < 15
From 52773af48408d299f69969b20304ee47c2993583 Mon Sep 17 00:00:00 2001
From: 076923 <076923@naver.com>
Date: Sun, 8 Nov 2026 14:40:53 +0900
Subject: [PATCH 7/7] 1.0.0: fix review findings - label colors, 16-bit
conversion, contour lists, CameraStream end, NumPy colors, blendImages
shapes, calibration usedViews; shared validators
---
CHANGELOG.md | 3 +-
cv2u/_validate.py | 92 +++++++++++++++++++++++++++++++++++-
cv2u/calib3d/calibrate.py | 53 ++++++++++++++++-----
cv2u/core/annotations.py | 89 +++++++++++++++++-----------------
cv2u/core/images.py | 13 ++---
cv2u/core/points.py | 17 ++-----
cv2u/dnn/inference.py | 9 ++--
cv2u/imgcodecs/meta.py | 13 ++++-
cv2u/imgproc/augment.py | 15 ++----
cv2u/imgproc/document.py | 28 ++++-------
cv2u/imgproc/draw.py | 10 ++--
cv2u/imgproc/stats.py | 77 +++++++++++++++++-------------
cv2u/imgproc/visualize.py | 40 ++++++++--------
cv2u/videoio/reader.py | 10 +++-
tests/test_annotations.py | 48 ++++++++++++++++++-
tests/test_calib3d.py | 25 +++++++++-
tests/test_dnn.py | 15 ++++++
tests/test_meta.py | 22 +++++++++
tests/test_stats.py | 15 ++++++
tests/test_validation.py | 56 ++++++++++++++++++++++
tests/test_videoio_reader.py | 18 ++++++-
tests/test_visualize.py | 25 ++++++++++
22 files changed, 517 insertions(+), 176 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fabe485..f44f843 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,7 +40,8 @@ semantic versioning and renames keep a deprecated alias (see [Design principles]
- `imencodeEx`, `imdecodeEx`, `convertImageFormat`: encode to `bytes` with errors raised, decode from any bytes-like object, and convert files between formats (alpha flattened for JPEG, orientation applied, `quality`).
- Color arithmetic (`imgproc`): `CSS_COLORS`, `lightenColor`, `darkenColor`, `blendColors`, `complementaryColor`, `invertColor`, `colorDistance`, `nearestColor`, `colorName`, `textColorFor`, `randomColors`, `gradientPalette`, `colormapPalette`.
- Point sets (`core`): `rotatePoints`, `scalePoints`, `translatePoints`, `flipPoints`, `normalizePoints`, `denormalizePoints`, `clipPoints`, `pointsBoundingBox`, `distancePoints`, `nearestPoints`, `orderPoints`, `polygonCentroid`, `angleBetween`, `lineIntersection`, `pointLineDistance`.
-- `Clusters` and `Letterbox` named tuples (see Changed).
+- `Clusters` and `Letterbox` named tuples (see Changed). `CameraCalibration.usedViews` lists the input views `calibrateCameraEx` used
+ (views without a board are skipped), and `reprojectionErrors` accepts the original corner list with `None` entries.
### Changed
- `DBSCAN` is now `dbscanColors(src, eps, minSamples=4)` and returns `Clusters(maps, centers)` like the other clusterers; labels are `0 .. k-1` with noise `-1` (was `(maps, labels)` with noise `0` and clusters from `1`). `clusterPoints` follows the same convention (noise `-1`, `int32` labels).
diff --git a/cv2u/_validate.py b/cv2u/_validate.py
index 39a732b..c86d008 100644
--- a/cv2u/_validate.py
+++ b/cv2u/_validate.py
@@ -1,11 +1,23 @@
"""Argument checks shared by the extensions: one wording for every function."""
import math
+import numbers
+from collections.abc import Sequence
from typing import Any
import numpy as np
-__all__ = ["check_channels", "check_color", "check_finite", "check_image_not_empty"]
+__all__ = [
+ "as_color",
+ "check_channels",
+ "check_color",
+ "check_finite",
+ "check_image_not_empty",
+ "check_size",
+ "check_uint8",
+ "is_single_color",
+ "to_uint8",
+]
def check_finite(name: str, value: float, *, positive: bool = False, nonnegative: bool = False) -> None:
@@ -53,3 +65,81 @@ def check_channels(name: str, image: np.ndarray) -> int:
if channels not in (1, 3, 4):
raise ValueError(f"{name} must have 1, 3 or 4 channels, got shape {image.shape}")
return channels
+
+
+def check_uint8(name: str, image: np.ndarray) -> int:
+ """Return the channel count of a non-empty 8-bit grayscale, BGR or BGRA image, or raise ``ValueError``.
+
+ OpenCV's drawing and document functions accept only ``uint8`` and fail (or draw garbage) on other depths.
+ """
+ if image.dtype != np.uint8:
+ raise ValueError(f"{name} must be an 8-bit (uint8) image, got dtype {image.dtype}")
+ check_image_not_empty(name, image)
+ return check_channels(name, image)
+
+
+def check_size(name: str, size: Sequence[float]) -> tuple[int, int]:
+ """Return a ``(width, height)`` size as positive ints, or raise ``ValueError``.
+
+ ``NaN``, infinities, zeros and negative values would surface later as an OpenCV assertion or an empty array.
+ """
+ if len(size) != 2:
+ raise ValueError(f"{name} must be (width, height), got {size!r}")
+ width, height = float(size[0]), float(size[1])
+ if not (math.isfinite(width) and math.isfinite(height)) or width < 1 or height < 1:
+ raise ValueError(f"{name} must be a positive (width, height) size, got {size!r}")
+ return int(width), int(height)
+
+
+def is_single_color(value: object) -> bool:
+ """Whether ``value`` is one color (a number, or 1, 3 or 4 numbers) rather than a sequence of colors.
+
+ Accepts Python and NumPy scalars and 1-D sequences or arrays of numbers, so a row of ``Clusters.centers``
+ (``np.array([0, 0, 255], np.uint8)``) counts as one color and is not mistaken for a palette of three. Two
+ numbers are never one color (no image has 2 channels): ``[200, 100]`` is two gray levels.
+ """
+ if isinstance(value, (bool, np.bool_)):
+ return False
+ if isinstance(value, (numbers.Real, np.number)):
+ return True
+ if isinstance(value, np.ndarray):
+ return value.ndim == 1 and value.size in (1, 3, 4) and np.issubdtype(value.dtype, np.number)
+ if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
+ return False
+ return len(value) in (1, 3, 4) and all(
+ isinstance(v, (numbers.Real, np.number)) and not isinstance(v, (bool, np.bool_)) for v in value
+ )
+
+
+def as_color(value: Any) -> float | tuple[float, ...]:
+ """One color as a Python ``float`` or tuple of floats, so OpenCV accepts it.
+
+ OpenCV rejects NumPy integer scalars and ``uint8`` arrays as colors ("Scalar value for argument 'color' is not
+ numeric"); a row of ``Clusters.centers`` or a ``np.uint8`` level has to be converted first.
+ """
+ if isinstance(value, (np.ndarray, np.generic)):
+ value = value.tolist()
+ if isinstance(value, numbers.Real):
+ return float(value)
+ return tuple(float(v) for v in value)
+
+
+def to_uint8(src: np.ndarray) -> np.ndarray:
+ """8-bit version of an image for formats and functions that only take ``uint8``, scaled by the dtype range.
+
+ Integer images are divided by their dtype peak (``65535`` for 16-bit). Float images are assumed to be in
+ ``[0, 1]``; when their maximum exceeds 1 they are scaled by that maximum instead. A plain ``astype(np.uint8)``
+ wraps 16-bit values around and ``cv.imwrite`` saturates them to white.
+ """
+ if src.dtype == np.uint8:
+ return src
+ values = src.astype(np.float64)
+ if np.issubdtype(src.dtype, np.integer):
+ peak = float(np.iinfo(src.dtype).max)
+ else:
+ finite = values[np.isfinite(values)]
+ top = float(np.max(finite)) if finite.size else 1.0
+ peak = top if top > 1.0 else 1.0
+ scaled = np.clip(np.nan_to_num(values) * (255.0 / peak), 0, 255)
+ out: np.ndarray = np.rint(scaled).astype(np.uint8)
+ return out
diff --git a/cv2u/calib3d/calibrate.py b/cv2u/calib3d/calibrate.py
index 0c71fb8..f94ede0 100644
--- a/cv2u/calib3d/calibrate.py
+++ b/cv2u/calib3d/calibrate.py
@@ -38,6 +38,10 @@ class CameraCalibration(NamedTuple):
"""Rotation vector of the board in each view, shape ``(3, 1)`` each."""
tvecs: tuple[np.ndarray, ...]
"""Translation vector of the board in each view, shape ``(3, 1)`` each."""
+ usedViews: tuple[int, ...] = ()
+ """Indices into the ``views`` given to :func:`calibrateCameraEx` of the views where the board was found;
+ ``rvecs[i]`` / ``tvecs[i]`` belong to ``views[usedViews[i]]``. Empty for calibrations loaded from files
+ written before this field existed."""
def _check_pattern(patternSize: tuple[int, int]) -> tuple[int, int]:
@@ -171,7 +175,8 @@ def calibrateCameraEx(
"""Calibrate a camera from chessboard images (or already detected corners).
The whole tutorial loop: detect the board in every image with :func:`findChessboardEx` (views where it is not
- found are skipped), build the object points with :func:`objectPointsGrid`, and run ``cv.calibrateCamera``.
+ found are skipped and listed by their absence in ``usedViews``), build the object points with
+ :func:`objectPointsGrid`, and run ``cv.calibrateCamera``.
Args:
views: Images of the chessboard, or corner arrays of shape ``(N, 2)`` such as :func:`findChessboardEx`
@@ -182,7 +187,8 @@ def calibrateCameraEx(
flags: ``cv.CALIB_*`` flags for ``cv.calibrateCamera``.
Returns:
- A :class:`CameraCalibration`.
+ A :class:`CameraCalibration`. Its ``rvecs`` / ``tvecs`` have one entry per *used* view, so when a board was
+ missed they are shorter than ``views``; ``usedViews`` maps them back to the input indices.
Raises:
ValueError: If fewer than 3 views contain the board, ``imageSize`` is missing for corner input, a corner
@@ -197,11 +203,14 @@ def calibrateCameraEx(
if not is_corners:
height, width = views[0].shape[:2]
size = (width, height)
- corners_list = [c for c in (findChessboardEx(view, (cols, rows)) for view in views) if c is not None]
+ found = [(i, findChessboardEx(view, (cols, rows))) for i, view in enumerate(views)]
+ used = [i for i, c in found if c is not None]
+ corners_list = [c for _, c in found if c is not None]
else:
if imageSize is None:
raise ValueError("imageSize is required when views are corner arrays")
size = (int(imageSize[0]), int(imageSize[1]))
+ used = list(range(len(views)))
corners_list = list(views)
if len(corners_list) < 3:
raise ValueError(f"the chessboard was found in only {len(corners_list)} view(s), need at least 3")
@@ -216,11 +225,15 @@ def calibrateCameraEx(
float(rms),
tuple(np.asarray(r, np.float64).reshape(3, 1) for r in rvecs),
tuple(np.asarray(t, np.float64).reshape(3, 1) for t in tvecs),
+ tuple(used),
)
def reprojectionErrors(
- calib: CameraCalibration, patternSize: tuple[int, int], squareSize: float, cornersList: Sequence[np.ndarray]
+ calib: CameraCalibration,
+ patternSize: tuple[int, int],
+ squareSize: float,
+ cornersList: Sequence[np.ndarray | None],
) -> np.ndarray:
"""Return the RMS reprojection error of every view, to spot the bad images in a calibration set.
@@ -229,23 +242,37 @@ def reprojectionErrors(
them and calibrate again.
Args:
- calib: The calibration whose ``rvecs`` / ``tvecs`` belong to ``cornersList`` (same views, same order).
+ calib: The calibration whose ``rvecs`` / ``tvecs`` belong to ``cornersList``.
patternSize: Inner corners as ``(columns, rows)``.
squareSize: Square size used for the calibration.
- cornersList: The detected corners of each view, ``(N, 2)`` each.
+ cornersList: The detected corners of each view, ``(N, 2)`` each: either one per used view (same order as
+ ``calib.rvecs``), or one per *original* view given to :func:`calibrateCameraEx` (then the views listed
+ in ``calib.usedViews`` are picked, so the output of :func:`findChessboardEx` for every image can be
+ passed as is, ``None`` entries included).
Returns:
- One RMS error in pixels per view, shape ``(len(cornersList),)`` float64.
+ One RMS error in pixels per used view, shape ``(len(calib.rvecs),)`` float64.
Raises:
- ValueError: If the number of views does not match ``calib.rvecs``, or a corner array has the wrong size.
+ ValueError: If the number of views matches neither ``calib.rvecs`` nor ``calib.usedViews``, a selected
+ entry is ``None``, or a corner array has the wrong size.
"""
cols, rows = _check_pattern(patternSize)
objp = objectPointsGrid((cols, rows), squareSize)
- if len(cornersList) != len(calib.rvecs):
- raise ValueError(f"cornersList has {len(cornersList)} views, but calib has {len(calib.rvecs)}")
+ count = len(calib.rvecs)
+ used = calib.usedViews
+ if len(cornersList) == count:
+ selected = list(cornersList)
+ elif len(used) == count and len(cornersList) > max(used, default=-1):
+ selected = [cornersList[i] for i in used]
+ else:
+ raise ValueError(f"cornersList has {len(cornersList)} views, but calib has {count} (usedViews: {len(used)})")
+ for index, corners in enumerate(selected):
+ if corners is None:
+ raise ValueError(f"view {index} has no corners (None), but it was used for the calibration")
errors = []
- for corners, rvec, tvec in zip(_as_corners(cornersList, cols * rows), calib.rvecs, calib.tvecs, strict=True):
+ views = _as_corners([c for c in selected if c is not None], cols * rows)
+ for corners, rvec, tvec in zip(views, calib.rvecs, calib.tvecs, strict=True):
projected, _ = cv2.projectPoints(objp, rvec, tvec, calib.cameraMatrix, calib.distCoeffs)
diff = projected.reshape(-1, 2) - corners.reshape(-1, 2)
errors.append(float(np.sqrt(np.mean(np.sum(diff**2, axis=1)))))
@@ -306,7 +333,7 @@ def saveCalibration(filename: str | os.PathLike[str], calib: CameraCalibration)
OpenCV's ``cv.FileStorage`` writes YAML/XML and cannot open non-ASCII paths on Windows; JSON is readable
everywhere and works with any path. Keys: ``cameraMatrix``, ``distCoeffs``, ``imageSize``, ``rms``,
- ``rvecs``, ``tvecs``.
+ ``rvecs``, ``tvecs``, ``usedViews``.
Args:
filename: Path to write to (``.json``).
@@ -319,6 +346,7 @@ def saveCalibration(filename: str | os.PathLike[str], calib: CameraCalibration)
"rms": calib.rms,
"rvecs": [r.reshape(-1).tolist() for r in calib.rvecs],
"tvecs": [t.reshape(-1).tolist() for t in calib.tvecs],
+ "usedViews": list(calib.usedViews),
}
with open(os.fspath(filename), "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
@@ -347,6 +375,7 @@ def loadCalibration(filename: str | os.PathLike[str]) -> CameraCalibration:
float(data["rms"]),
tuple(np.asarray(r, np.float64).reshape(3, 1) for r in data.get("rvecs", [])),
tuple(np.asarray(t, np.float64).reshape(3, 1) for t in data.get("tvecs", [])),
+ tuple(int(i) for i in data.get("usedViews", [])),
)
except (KeyError, TypeError) as exc:
raise ValueError(f"not a calibration file: {os.fspath(filename)!r} ({exc})") from exc
diff --git a/cv2u/core/annotations.py b/cv2u/core/annotations.py
index 41b58c1..b640dd7 100644
--- a/cv2u/core/annotations.py
+++ b/cv2u/core/annotations.py
@@ -19,9 +19,10 @@
import numpy as np
from numpy.typing import ArrayLike
-from .._validate import check_color, check_finite, check_image_not_empty
+from .._validate import as_color, check_color, check_finite, check_image_not_empty, check_size, is_single_color
from ..imgproc.color import distinctColors
from ..imgproc.contour import approxContour, asContour, contoursToMask
+from ..imgproc.draw import _luminance
from ..imgproc.mask import _foreground
from .boxes import _boxes
@@ -52,13 +53,6 @@
Color = float | Sequence[float]
-def _size(size: tuple[int, int]) -> tuple[int, int]:
- width, height = size
- if width < 1 or height < 1:
- raise ValueError(f"size must be at least 1x1, got {size}")
- return int(width), int(height)
-
-
def _polygon(polygon: ArrayLike, name: str = "polygon") -> np.ndarray:
"""One polygon as a float64 ``(N, 2)`` array (accepts ``(N, 1, 2)`` contours and point lists)."""
array = np.asarray(polygon, dtype=np.float64)
@@ -66,27 +60,41 @@ def _polygon(polygon: ArrayLike, name: str = "polygon") -> np.ndarray:
raise ValueError(f"{name} must not be empty")
if array.shape[-1] != 2:
raise ValueError(f"{name} must have 2 coordinates (x, y) per point, got shape {array.shape}")
+ if array.ndim > 3 or (array.ndim == 3 and array.shape[1] != 1):
+ raise ValueError(f"{name} must be (N, 2) points or an (N, 1, 2) contour, got shape {array.shape}")
if not np.all(np.isfinite(array)):
raise ValueError(f"{name} must be finite")
return array.reshape(-1, 2)
def _polygons(polygons: Sequence[ArrayLike] | np.ndarray, name: str = "polygons") -> list[np.ndarray]:
- """A sequence of polygons (or one polygon, as an ``(N, 2)`` array or point list) as float64 ``(N, 2)`` arrays."""
- if not isinstance(polygons, np.ndarray):
- try:
- array = np.asarray(polygons, dtype=np.float64)
- except (ValueError, TypeError): # ragged: polygons of different lengths
- return [_polygon(p, name) for p in polygons]
- else:
- array = polygons
- if array.size == 0 and array.ndim <= 1:
+ """A sequence of polygons (or one polygon, as an ``(N, 2)`` array or point list) as float64 ``(N, 2)`` arrays.
+
+ Each polygon may be an ``(N, 2)`` array, an ``(N, 1, 2)`` contour or a list of ``(x, y)`` points, and the
+ polygons may have different lengths. The sequence is walked element-wise: ``np.asarray`` on the whole list
+ would turn equal-length contours into a 4-D array and ragged ones into an error.
+ """
+ if isinstance(polygons, np.ndarray):
+ if polygons.size == 0 and polygons.ndim <= 1:
+ return []
+ if polygons.ndim == 2 and polygons.shape[-1] == 2:
+ return [_polygon(polygons, name)] # one polygon
+ if polygons.ndim == 3 and polygons.shape[-1] == 2:
+ return [_polygon(p, name) for p in polygons] # equal-length polygons, or one (N, 1, 2) contour
+ raise ValueError(f"{name} must be a sequence of (N, 2) polygons, got shape {polygons.shape}")
+ items = list(polygons)
+ if len(items) == 0:
return []
- if array.ndim == 2 and array.shape[-1] == 2:
- return [_polygon(array, name)] # one polygon
- if array.ndim == 3 and array.shape[-1] == 2:
- return [_polygon(p, name) for p in array] # equal-length polygons, or one (N, 1, 2) contour
- raise ValueError(f"{name} must be a sequence of (N, 2) polygons, got shape {array.shape}")
+ if _is_point(items[0]):
+ return [_polygon(items, name)] # one polygon as a list of (x, y) points
+ return [_polygon(p, name) for p in items]
+
+
+def _is_point(item: object) -> bool:
+ """Whether a sequence element is one ``(x, y)`` point rather than a polygon."""
+ if isinstance(item, np.ndarray):
+ return item.ndim == 1
+ return isinstance(item, Sequence) and len(item) == 2 and all(isinstance(v, (int, float, np.number)) for v in item)
def _label_map(labels: np.ndarray, name: str = "labels") -> np.ndarray:
@@ -164,7 +172,7 @@ def polygonsToMask(polygons: Sequence[ArrayLike] | np.ndarray, size: tuple[int,
"""
if not 1 <= value <= 255:
raise ValueError(f"value must be between 1 and 255, got {value}")
- mask = contoursToMask([asContour(p) for p in _polygons(polygons)], _size(size))
+ mask = contoursToMask([asContour(p) for p in _polygons(polygons)], check_size("size", size))
if value != 255:
mask[mask != 0] = value
return mask
@@ -377,7 +385,7 @@ def boxesToYolo(boxes: ArrayLike, size: tuple[int, int], classIds: ArrayLike | N
Raises:
ValueError: If ``size`` is not positive, the boxes are invalid, or ``classIds`` has the wrong length.
"""
- width, height = _size(size)
+ width, height = check_size("size", size)
array = _boxes(boxes, "boxes") if np.size(boxes) else np.zeros((0, 4))
rows = np.stack(
[
@@ -410,7 +418,7 @@ def yoloToBoxes(rows: ArrayLike, size: tuple[int, int]) -> tuple[np.ndarray, np.
Raises:
ValueError: If ``size`` is not positive or the rows do not have 4 or more values.
"""
- width, height = _size(size)
+ width, height = check_size("size", size)
array = np.asarray(rows, dtype=np.float64)
if array.size == 0:
return np.zeros((0, 4), dtype=np.float64), np.zeros(0, dtype=np.int64)
@@ -443,7 +451,7 @@ def readYoloLabels(filename: str | os.PathLike[str], size: tuple[int, int]) -> t
Raises:
ValueError: If ``size`` is not positive, or a line does not have at least 5 numbers.
"""
- _size(size)
+ check_size("size", size)
path = Path(filename)
rows: list[list[float]] = []
if path.is_file():
@@ -656,16 +664,14 @@ def drawPolygons(
palette: list[Color]
if color is None:
palette = list(distinctColors(max(count, 1)))
- elif isinstance(color, (int, float)) or (len(color) in (3, 4) and all(isinstance(c, (int, float)) for c in color)):
- palette = [color] * max(count, 1) # type: ignore[list-item]
+ elif is_single_color(color):
+ palette = [as_color(color)] * max(count, 1)
else:
- palette = list(color)
+ palette = [as_color(c) for c in color] # type: ignore[union-attr]
if len(palette) != count:
raise ValueError(f"color must have one entry per polygon, got {len(palette)} for {count} polygons")
for entry in palette:
- check_color(
- "color", [float(entry)] if isinstance(entry, (int, float)) else [float(c) for c in entry], src.dtype
- )
+ check_color("color", [entry] if isinstance(entry, float) else list(entry), src.dtype)
if count == 0 or alpha == 0:
return src
canvas = src.copy() if alpha < 1 else src
@@ -680,7 +686,9 @@ def drawPolygons(
(tw, th), baseline = cv2.getTextSize(labels[i], cv2.FONT_HERSHEY_SIMPLEX, fontScale, 1)
top = max(y - th - baseline - 2, 0)
cv2.rectangle(canvas, (x, top), (x + tw + 2, top + th + baseline + 2), palette[i], cv2.FILLED)
- text_color = 0 if _luminance(palette[i]) > 140 else 255
+ # A scalar 255 would be expanded by OpenCV to (255, 0, 0): blue text on BGR images.
+ level = 0 if _luminance(palette[i]) > 140 else 255
+ text_color: Color = level if canvas.ndim == 2 else (level,) * canvas.shape[2]
cv2.putText(
canvas, labels[i], (x + 1, top + th + 1), cv2.FONT_HERSHEY_SIMPLEX, fontScale, text_color, 1, lineType
)
@@ -689,15 +697,6 @@ def drawPolygons(
return src
-def _luminance(color: Color) -> float:
- if isinstance(color, (int, float)):
- return float(color)
- values = [float(c) for c in color]
- if len(values) < 3:
- return values[0]
- return 0.114 * values[0] + 0.587 * values[1] + 0.299 * values[2]
-
-
def drawSegmentation(
src: np.ndarray,
labels: np.ndarray,
@@ -765,7 +764,7 @@ def flipBoxes(boxes: ArrayLike, size: tuple[int, int], flipCode: int) -> np.ndar
Raises:
ValueError: If ``size`` is not positive, the boxes are invalid, or ``flipCode`` is not 0, 1 or -1.
"""
- width, height = _size(size)
+ width, height = check_size("size", size)
code = _flip_code(flipCode)
single = np.ndim(boxes) == 1 and np.size(boxes) > 0
out = _boxes(boxes, "boxes").copy() if np.size(boxes) else np.zeros((0, 4))
@@ -793,7 +792,7 @@ def _flip_polygon(points: ArrayLike, size: tuple[int, int], flipCode: int) -> np
Raises:
ValueError: If ``size`` is not positive, the points are empty or not 2-D, or ``flipCode`` is not 0, 1 or -1.
"""
- width, height = _size(size)
+ width, height = check_size("size", size)
code = _flip_code(flipCode)
out = _polygon(points, "points").copy()
if code in (1, -1):
@@ -820,6 +819,6 @@ def flipPolygons(polygons: Sequence[ArrayLike], size: tuple[int, int], flipCode:
Raises:
ValueError: If ``size`` is not positive, a polygon is empty or not 2-D, or ``flipCode`` is not 0, 1 or -1.
"""
- _size(size)
+ check_size("size", size)
_flip_code(flipCode)
return [_flip_polygon(p, size, flipCode) for p in _polygons(polygons)]
diff --git a/cv2u/core/images.py b/cv2u/core/images.py
index c351ebe..f92ba45 100644
--- a/cv2u/core/images.py
+++ b/cv2u/core/images.py
@@ -6,20 +6,13 @@
import numpy as np
from numpy.typing import DTypeLike
-from .._validate import check_color
+from .._validate import check_color, check_size
__all__ = ["imcolor", "imcolorLike", "makeGradient"]
GradientDirection = Literal["horizontal", "vertical", "raster"]
-def _size(size: tuple[int, int]) -> tuple[int, int]:
- width, height = size
- if width < 1 or height < 1:
- raise ValueError(f"size must be at least 1x1, got {size}")
- return int(width), int(height)
-
-
def _color_values(name: str, color: float | Sequence[float], channels: int, dtype: DTypeLike) -> np.ndarray:
values = np.atleast_1d(np.asarray(color, dtype=np.float64)).ravel()
if values.size not in (1, channels):
@@ -52,7 +45,7 @@ def makeGradient(
ValueError: If ``size`` is not positive, ``channels`` is not 1 or 3, a value is outside ``[0, 255]`` or
does not match the channel count, or ``direction`` is unknown.
"""
- width, height = _size(size)
+ width, height = check_size("size", size)
if channels not in (1, 3):
raise ValueError(f"channels must be 1 or 3, got {channels}")
lo = _color_values("start", start, channels, np.uint8)
@@ -85,7 +78,7 @@ def imcolor(
ValueError: If ``size`` is not positive, ``channels`` is not 1, 3 or 4, or ``color`` is not finite, does not
match the channel count, or is outside the range of ``dtype``.
"""
- width, height = _size(size)
+ width, height = check_size("size", size)
if channels not in (1, 3, 4):
raise ValueError(f"channels must be 1, 3 or 4, got {channels}")
values = _color_values("color", color, channels, dtype)
diff --git a/cv2u/core/points.py b/cv2u/core/points.py
index 540fe98..5922907 100644
--- a/cv2u/core/points.py
+++ b/cv2u/core/points.py
@@ -13,7 +13,7 @@
import numpy as np
from numpy.typing import ArrayLike
-from .._validate import check_finite
+from .._validate import check_finite, check_size
from ..imgproc.geometry import _order_corners
__all__ = [
@@ -45,13 +45,6 @@ def _points(points: ArrayLike, name: str = "points") -> tuple[np.ndarray, tuple[
return array.reshape(-1, 2), array.shape
-def _size(size: tuple[int, int]) -> tuple[float, float]:
- width, height = float(size[0]), float(size[1])
- if not (math.isfinite(width) and math.isfinite(height)) or width <= 0 or height <= 0:
- raise ValueError(f"size must be positive (width, height), got {size}")
- return width, height
-
-
def _point(point: ArrayLike, name: str) -> tuple[float, float]:
pts, shape = _points(point, name)
if pts.shape[0] != 1:
@@ -149,7 +142,7 @@ def flipPoints(points: ArrayLike, size: tuple[int, int], flipCode: int) -> np.nd
ValueError: If ``size`` is not positive.
"""
pts, shape = _points(points)
- width, height = _size(size)
+ width, height = check_size("size", size)
out = pts.copy()
if flipCode != 0:
out[:, 0] = width - 1 - out[:, 0]
@@ -172,7 +165,7 @@ def normalizePoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray:
ValueError: If ``size`` is not positive.
"""
pts, shape = _points(points)
- out: np.ndarray = pts / _size(size)
+ out: np.ndarray = pts / check_size("size", size)
return out.reshape(shape)
@@ -190,7 +183,7 @@ def denormalizePoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray:
ValueError: If ``size`` is not positive.
"""
pts, shape = _points(points)
- out: np.ndarray = pts * _size(size)
+ out: np.ndarray = pts * check_size("size", size)
return out.reshape(shape)
@@ -208,7 +201,7 @@ def clipPoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray:
ValueError: If ``size`` is not positive.
"""
pts, shape = _points(points)
- width, height = _size(size)
+ width, height = check_size("size", size)
out: np.ndarray = np.clip(pts, 0, (width - 1, height - 1))
return out.reshape(shape)
diff --git a/cv2u/dnn/inference.py b/cv2u/dnn/inference.py
index 4c6f959..16d1f8d 100644
--- a/cv2u/dnn/inference.py
+++ b/cv2u/dnn/inference.py
@@ -335,14 +335,15 @@ def loadModel(
raise FileNotFoundError(f"config file not found: {config_path}")
ext = os.path.splitext(model_path)[1].lower()
- buffer = np.fromfile(model_path, dtype=np.uint8)
+ # Only the formats with a buffer reader (unicode-safe paths) are read into memory; the others let OpenCV
+ # open the path itself, so a large Caffe or Darknet model is not loaded twice.
if ext == ".onnx" and hasattr(dnn, "readNetFromONNX"):
- net = dnn.readNetFromONNX(buffer)
+ net = dnn.readNetFromONNX(np.fromfile(model_path, dtype=np.uint8))
elif ext == ".tflite" and hasattr(dnn, "readNetFromTFLite"):
- net = dnn.readNetFromTFLite(buffer)
+ net = dnn.readNetFromTFLite(np.fromfile(model_path, dtype=np.uint8))
elif ext == ".pb" and hasattr(dnn, "readNetFromTensorflow"):
config_buffer = np.zeros(0, np.uint8) if config_path is None else np.fromfile(config_path, dtype=np.uint8)
- net = dnn.readNetFromTensorflow(buffer, config_buffer)
+ net = dnn.readNetFromTensorflow(np.fromfile(model_path, dtype=np.uint8), config_buffer)
else:
net = dnn.readNet(model_path) if config_path is None else dnn.readNet(model_path, config_path)
diff --git a/cv2u/imgcodecs/meta.py b/cv2u/imgcodecs/meta.py
index 77bec07..4ebdc15 100644
--- a/cv2u/imgcodecs/meta.py
+++ b/cv2u/imgcodecs/meta.py
@@ -9,6 +9,7 @@
import numpy as np
from PIL import Image, UnidentifiedImageError
+from .._validate import to_uint8
from ..imgproc.color import flattenAlpha
from ..imgproc.resize import resizeEx
from .files import imreadEx, imwriteEx
@@ -290,6 +291,10 @@ def imdecodeEx(data: bytes | bytearray | memoryview | np.ndarray, flags: int = c
_ALPHA_FORMATS = frozenset({".png", ".webp", ".tif", ".tiff", ".avif", ".bmp", ".jp2"})
+_UINT16_FORMATS = frozenset({".png", ".tif", ".tiff", ".jp2", ".pxm", ".pgm", ".ppm", ".pnm", ".pfm"})
+"""Formats whose OpenCV encoder keeps 16-bit samples without loss (PFM stores them as floats)."""
+_FLOAT_FORMATS = frozenset({".exr", ".hdr", ".pic", ".pfm", ".tif", ".tiff"})
+"""Formats whose OpenCV encoder stores 32-bit float samples (TIFF also takes 16-bit and 64-bit floats)."""
_QUALITY_FLAGS = {
".jpg": cv2.IMWRITE_JPEG_QUALITY,
".jpeg": cv2.IMWRITE_JPEG_QUALITY,
@@ -311,7 +316,10 @@ def convertImageFormat(
The file is read as stored (``cv.IMREAD_UNCHANGED``: alpha channel and 16-bit depth are kept) with the EXIF
orientation applied, since the tag is not carried over to the new file. Transparent images are composited
onto ``background`` with :func:`flattenAlpha` when the target format has no alpha (JPEG), where
- ``cv.imwrite`` would silently drop the alpha channel and expose the hidden pixels.
+ ``cv.imwrite`` would silently drop the alpha channel and expose the hidden pixels. 16-bit and float images
+ are scaled to 8-bit (``uint16`` by ``1 / 257``, floats from ``[0, 1]`` or by their maximum when above 1)
+ when the target format cannot store the depth (JPEG, WebP, AVIF, BMP, GIF ...), where ``cv.imwrite`` would
+ saturate them to white; PNG / TIFF / JPEG 2000 / PNM / PFM keep 16-bit and EXR / HDR / PFM / TIFF keep floats.
Args:
src: Path of the image to convert.
@@ -335,6 +343,9 @@ def convertImageFormat(
return False
if img.ndim == 3 and img.shape[2] == 4 and ext not in _ALPHA_FORMATS:
img = flattenAlpha(img, background)
+ keeps_depth = ext in _FLOAT_FORMATS if np.issubdtype(img.dtype, np.floating) else ext in _UINT16_FORMATS
+ if img.dtype != np.uint8 and not keeps_depth:
+ img = to_uint8(img)
params: list[int] = []
if quality is not None and ext in _QUALITY_FLAGS:
params = [_QUALITY_FLAGS[ext], int(quality)]
diff --git a/cv2u/imgproc/augment.py b/cv2u/imgproc/augment.py
index 1dc0a58..8e22e28 100644
--- a/cv2u/imgproc/augment.py
+++ b/cv2u/imgproc/augment.py
@@ -13,7 +13,7 @@
import numpy as np
from numpy.typing import ArrayLike
-from .._validate import check_color, check_finite, check_image_not_empty
+from .._validate import check_color, check_finite, check_image_not_empty, check_size
from ..core.boxes import clipBoxes
from .adjust import adjustBrightnessContrast, adjustHSV
@@ -103,13 +103,6 @@ def _fill_value(fill: Any, src: np.ndarray) -> list[float]:
return values
-def _size(size: tuple[int, int], name: str = "size") -> tuple[int, int]:
- width, height = int(size[0]), int(size[1])
- if width <= 0 or height <= 0:
- raise ValueError(f"{name} must be positive, got {size}")
- return width, height
-
-
# --- deterministic degradations ------------------------------------------------------------------------------------
@@ -297,7 +290,7 @@ def randomErase(
patch = (size, size)
else:
patch = (int(size[0]), int(size[1]))
- pw, ph = _size(patch)
+ pw, ph = check_size("size", patch)
if pw > w or ph > h:
raise ValueError(f"size must not exceed the image size ({w}x{h}), got {patch}")
if count < 0:
@@ -397,7 +390,7 @@ def randomCrop(
ValueError: If ``src`` is empty, ``size`` is not positive or exceeds the image, or ``boxes`` is malformed.
"""
_check_image(src)
- cw, ch = _size(size)
+ cw, ch = check_size("size", size)
h, w = src.shape[:2]
if cw > w or ch > h:
raise ValueError(f"size must not exceed the image size ({w}x{h}), got {size}")
@@ -750,7 +743,7 @@ def mosaic(
first = images[0]
for i, image in enumerate(images):
_same_layout(first, image, "images[0]", f"images[{i}]")
- out_w, out_h = _size(size)
+ out_w, out_h = check_size("size", size)
rng = np.random.default_rng(seed)
cx = int(rng.integers(out_w // 4, out_w - out_w // 4 + 1))
cy = int(rng.integers(out_h // 4, out_h - out_h // 4 + 1))
diff --git a/cv2u/imgproc/document.py b/cv2u/imgproc/document.py
index 60ed133..31560ae 100644
--- a/cv2u/imgproc/document.py
+++ b/cv2u/imgproc/document.py
@@ -11,7 +11,7 @@
import cv2
import numpy as np
-from .._validate import check_finite, check_image_not_empty
+from .._validate import check_finite, check_image_not_empty, check_uint8
from .adjust import autoContrast
from .binary import binarize
from .color import toGray
@@ -36,14 +36,6 @@
EnhanceMode = Literal["gray", "color", "binary"]
-def _check_uint8(name: str, src: np.ndarray) -> None:
- check_image_not_empty(name, src)
- if src.dtype != np.uint8:
- raise ValueError(f"{name} must be an 8-bit (uint8) image, got dtype {src.dtype}")
- if src.ndim not in (2, 3):
- raise ValueError(f"{name} must be a grayscale or color image, got shape {src.shape}")
-
-
def _check_odd(name: str, value: int, minimum: int = 3) -> None:
if value < minimum or value % 2 == 0:
raise ValueError(f"{name} must be odd and at least {minimum}, got {value}")
@@ -75,7 +67,7 @@ def removeShadow(src: np.ndarray, kernelSize: int = 21, blurSize: int = 21) -> n
Raises:
ValueError: If ``src`` is empty or not 8-bit, or ``kernelSize``/``blurSize`` is not a valid kernel size.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
if kernelSize < 1:
raise ValueError(f"kernelSize must be positive, got {kernelSize}")
_check_odd("blurSize", blurSize)
@@ -142,7 +134,7 @@ def sauvolaThreshold(
Raises:
ValueError: If ``src`` is empty or not 8-bit, ``windowSize`` is not odd, or ``k``/``r`` is not finite.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
_check_odd("windowSize", windowSize)
check_finite("k", k)
check_finite("r", r, positive=True)
@@ -169,7 +161,7 @@ def niblackThreshold(src: np.ndarray, windowSize: int = 25, k: float = -0.2, inv
Raises:
ValueError: If ``src`` is empty or not 8-bit, ``windowSize`` is not odd, or ``k`` is not finite.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
_check_odd("windowSize", windowSize)
check_finite("k", k)
gray = toGray(src)
@@ -209,7 +201,7 @@ def removeLines(
ValueError: If ``src`` is empty or not 8-bit, ``minLength`` is not positive, or ``thickness`` is not
positive.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
if minLength is not None:
check_finite("minLength", minLength, positive=True)
if thickness < 1:
@@ -250,7 +242,7 @@ def _text_regions(
) -> np.ndarray:
"""Boxes of ink regions after dilating with ``ksize``, sorted top to bottom; the kernel defaults to
``defaults`` times the median character height."""
- _check_uint8("src", src)
+ check_uint8("src", src)
if minHeight < 1:
raise ValueError(f"minHeight must be positive, got {minHeight}")
ink = _ink_mask(src)
@@ -343,7 +335,7 @@ def removeBorder(src: np.ndarray, threshold: float | None = None, margin: int =
Raises:
ValueError: If ``src`` is empty or not 8-bit, or ``threshold`` is not finite.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
if threshold is not None:
check_finite("threshold", threshold)
gray = toGray(src)
@@ -379,7 +371,7 @@ def detectPage(src: np.ndarray, minAreaRatio: float = 0.2) -> np.ndarray | None:
Raises:
ValueError: If ``src`` is empty or not 8-bit, or ``minAreaRatio`` is not in ``[0, 1]``.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
check_finite("minAreaRatio", minAreaRatio)
if not 0 <= minAreaRatio <= 1:
raise ValueError(f"minAreaRatio must be in [0, 1], got {minAreaRatio}")
@@ -425,7 +417,7 @@ def enhanceDocument(src: np.ndarray, mode: EnhanceMode = "gray") -> np.ndarray:
Raises:
ValueError: If ``src`` is empty or not 8-bit, or ``mode`` is unknown.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
if mode not in ("gray", "color", "binary"):
raise ValueError(f"mode must be 'gray', 'color' or 'binary', got {mode!r}")
image = src if mode == "color" else toGray(src)
@@ -513,7 +505,7 @@ def removeSpeckles(src: np.ndarray, maxArea: int = 10) -> np.ndarray:
Raises:
ValueError: If ``src`` is empty or not 8-bit, or ``maxArea`` is negative.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
if maxArea < 0:
raise ValueError(f"maxArea must not be negative, got {maxArea}")
ink = _ink_mask(src)
diff --git a/cv2u/imgproc/draw.py b/cv2u/imgproc/draw.py
index 8281539..6b523da 100644
--- a/cv2u/imgproc/draw.py
+++ b/cv2u/imgproc/draw.py
@@ -7,7 +7,7 @@
import numpy as np
from PIL import Image, ImageDraw
-from .._validate import check_channels, check_finite, check_image_not_empty
+from .._validate import as_color, check_channels, check_finite, check_image_not_empty, is_single_color
from .puttext import _load_font
__all__ = [
@@ -391,12 +391,10 @@ def drawBoxes(
palette: list[Color]
if colors is None:
palette = list(distinctColors(max(count, 1)))
- elif isinstance(colors, (int, float)) or (
- len(colors) in (3, 4) and all(isinstance(c, (int, float)) for c in colors)
- ):
- palette = [colors] * max(count, 1) # type: ignore[list-item]
+ elif is_single_color(colors):
+ palette = [as_color(colors)] * max(count, 1)
else:
- palette = list(colors)
+ palette = [as_color(c) for c in colors] # type: ignore[union-attr]
if len(palette) != count:
raise ValueError(f"colors must have one entry per box, got {len(palette)} for {count} boxes")
for i, box in enumerate(array):
diff --git a/cv2u/imgproc/stats.py b/cv2u/imgproc/stats.py
index 35410cc..9315c8f 100644
--- a/cv2u/imgproc/stats.py
+++ b/cv2u/imgproc/stats.py
@@ -6,7 +6,7 @@
import cv2
import numpy as np
-from .._validate import check_finite, check_image_not_empty
+from .._validate import check_finite, check_image_not_empty, to_uint8
from .color import toBGR, toGray
from .quality import sharpnessScore
@@ -41,6 +41,32 @@ def _gray64(src: np.ndarray) -> np.ndarray:
return toGray(src).astype(np.float64)
+def _brightness(gray: np.ndarray, peak: float) -> float:
+ return float(gray.mean() / peak)
+
+
+def _contrast(gray: np.ndarray, peak: float) -> float:
+ return float(gray.std() / peak)
+
+
+def _sharpness(gray: np.ndarray) -> float:
+ laplacian = cv2.Laplacian(gray, cv2.CV_64F)
+ return float(laplacian.var())
+
+
+def _entropy(counts: np.ndarray) -> float:
+ probabilities = counts[counts > 0] / counts.sum()
+ return float(-(probabilities * np.log2(probabilities)).sum())
+
+
+def _is_grayscale(color: np.ndarray, tolerance: float) -> bool:
+ if color.shape[2] == 1:
+ return True
+ values = color.astype(np.float64)
+ spread = values.max(axis=2) - values.min(axis=2)
+ return bool(np.max(spread) <= tolerance)
+
+
def _color_channels(src: np.ndarray) -> np.ndarray:
"""The image without its alpha channel, as a ``(h, w, c)`` array."""
check_image_not_empty("src", src)
@@ -51,15 +77,6 @@ def _color_channels(src: np.ndarray) -> np.ndarray:
return src[..., :3]
-def _to_uint8(src: np.ndarray) -> np.ndarray:
- """8-bit version of the image for OpenCV functions that only accept ``uint8`` (scaled by the dtype peak)."""
- if src.dtype == np.uint8:
- return src
- scaled = np.clip(src.astype(np.float64) * (255.0 / _peak(src.dtype)), 0, 255)
- out: np.ndarray = np.rint(scaled).astype(np.uint8)
- return out
-
-
def _check_pair(a: np.ndarray, b: np.ndarray) -> None:
if a.shape != b.shape:
raise ValueError(f"a and b must have the same shape, got {a.shape} and {b.shape}")
@@ -115,12 +132,7 @@ def isGrayscale(src: np.ndarray, tolerance: float = 0) -> bool:
ValueError: If ``src`` is empty, has a wrong channel count, or ``tolerance`` is negative.
"""
check_finite("tolerance", tolerance, nonnegative=True)
- color = _color_channels(src)
- if color.shape[2] == 1:
- return True
- values = color.astype(np.float64)
- spread = values.max(axis=2) - values.min(axis=2)
- return bool(np.max(spread) <= tolerance)
+ return _is_grayscale(_color_channels(src), tolerance)
def isBlank(src: np.ndarray, tolerance: float = 2.0) -> bool:
@@ -168,7 +180,7 @@ def brightnessScore(src: np.ndarray) -> float:
Raises:
ValueError: If ``src`` is empty or has a wrong channel count.
"""
- return float(_gray64(src).mean() / _peak(src.dtype))
+ return _brightness(_gray64(src), _peak(src.dtype))
def contrastScore(src: np.ndarray) -> float:
@@ -183,7 +195,7 @@ def contrastScore(src: np.ndarray) -> float:
Raises:
ValueError: If ``src`` is empty or has a wrong channel count.
"""
- return float(_gray64(src).std() / _peak(src.dtype))
+ return _contrast(_gray64(src), _peak(src.dtype))
def colorfulness(src: np.ndarray) -> float:
@@ -237,11 +249,11 @@ def exposureScore(src: np.ndarray, lowThreshold: float = 0.05, highThreshold: fl
return float((gray <= lowThreshold).mean()), float((gray >= highThreshold).mean())
-def _gray_histogram(src: np.ndarray, bins: int) -> np.ndarray:
- gray = toGray(src)
+def _gray_histogram(gray: np.ndarray, bins: int, peak: float) -> np.ndarray:
+ """Histogram of a grayscale image (any dtype) over ``[0, peak]``; ``float64`` input is binned directly."""
if gray.dtype == np.uint8 and bins == 256:
return np.bincount(gray.ravel(), minlength=256).astype(np.float64)
- counts, _ = np.histogram(gray.astype(np.float64), bins=bins, range=(0.0, _peak(src.dtype)))
+ counts, _ = np.histogram(gray.astype(np.float64), bins=bins, range=(0.0, peak))
return counts.astype(np.float64)
@@ -260,9 +272,7 @@ def entropy(src: np.ndarray, bins: int = 256) -> float:
"""
if bins < 1:
raise ValueError(f"bins must be at least 1, got {bins}")
- counts = _gray_histogram(src, bins)
- probabilities = counts[counts > 0] / counts.sum()
- return float(-(probabilities * np.log2(probabilities)).sum())
+ return _entropy(_gray_histogram(toGray(src), bins, _peak(src.dtype)))
_NOISE_KERNEL = np.array([[1, -2, 1], [-2, 4, -2], [1, -2, 1]], dtype=np.float64)
@@ -401,7 +411,7 @@ def histogramCompare(
raise ValueError(f'colorSpace must be "hsv", "bgr" or "gray", got {colorSpace!r}')
def histogram(src: np.ndarray) -> np.ndarray:
- image = _to_uint8(src)
+ image = to_uint8(src)
if colorSpace == "gray":
image, channels, ranges = toGray(image), [0], [0.0, 256.0]
elif colorSpace == "hsv":
@@ -433,7 +443,7 @@ def dominantHue(src: np.ndarray, bins: int = 36) -> float:
color = _color_channels(src)
if color.shape[2] == 1:
return 0.0
- hsv = cv2.cvtColor(toBGR(_to_uint8(src)), cv2.COLOR_BGR2HSV_FULL)
+ hsv = cv2.cvtColor(toBGR(to_uint8(src)), cv2.COLOR_BGR2HSV_FULL)
hue = hsv[..., 0].astype(np.float64) * (360.0 / 256.0)
weight = hsv[..., 1].astype(np.float64) * (hsv[..., 2].astype(np.float64) / 255.0)
if weight.sum() == 0:
@@ -484,10 +494,13 @@ def imageStats(src: np.ndarray) -> ImageStats:
Raises:
ValueError: If ``src`` is empty or has a wrong channel count.
"""
- _color_channels(src)
+ color = _color_channels(src)
image = src[..., np.newaxis] if src.ndim == 2 else src
flat = image.reshape(-1, image.shape[2]).astype(np.float64)
height, width = src.shape[:2]
+ peak = _peak(src.dtype)
+ gray8 = toGray(src) # converted once; every gray-based metric derives from it
+ gray = gray8.astype(np.float64)
return ImageStats(
width=int(width),
height=int(height),
@@ -497,9 +510,9 @@ def imageStats(src: np.ndarray) -> ImageStats:
std=tuple(float(v) for v in flat.std(axis=0)),
minVal=float(np.min(flat)),
maxVal=float(np.max(flat)),
- brightness=brightnessScore(src),
- contrast=contrastScore(src),
- sharpness=sharpnessScore(src),
- entropy=entropy(src),
- isGray=isGrayscale(src),
+ brightness=_brightness(gray, peak),
+ contrast=_contrast(gray, peak),
+ sharpness=_sharpness(gray),
+ entropy=_entropy(_gray_histogram(gray8, 256, peak)),
+ isGray=_is_grayscale(color, 0),
)
diff --git a/cv2u/imgproc/visualize.py b/cv2u/imgproc/visualize.py
index 3bdccc5..b74f10b 100644
--- a/cv2u/imgproc/visualize.py
+++ b/cv2u/imgproc/visualize.py
@@ -6,7 +6,15 @@
import cv2
import numpy as np
-from .._validate import check_channels, check_color, check_finite, check_image_not_empty
+from .._validate import (
+ as_color,
+ check_channels,
+ check_color,
+ check_finite,
+ check_image_not_empty,
+ check_uint8,
+ is_single_color,
+)
from ..core.compose import hconcatEx, vconcatEx
from .color import distinctColors, toBGR, toBGRA, toGray
from .draw import Color, _bgr, _luminance
@@ -44,13 +52,6 @@
_FONT = cv2.FONT_HERSHEY_SIMPLEX
-def _check_uint8(name: str, img: np.ndarray) -> None:
- if img.dtype != np.uint8:
- raise ValueError(f"{name} must be an 8-bit (uint8) image, got dtype {img.dtype}")
- check_image_not_empty(name, img)
- check_channels(name, img)
-
-
def _check_unit(name: str, value: float) -> None:
check_finite(name, value)
if not 0.0 <= value <= 1.0:
@@ -178,7 +179,7 @@ def heatmap(
Raises:
ValueError: If ``src`` is not 8-bit, ``values`` is not 2-D, or ``alpha`` is outside ``[0, 1]``.
"""
- _check_uint8("src", src)
+ check_uint8("src", src)
_check_unit("alpha", alpha)
colored = applyColorMapEx(values, colormap, normalize)
height, width = src.shape[:2]
@@ -399,9 +400,9 @@ def drawRotatedBoxes(
def _palette(colors: Sequence[Color] | Color | None, count: int) -> list[Color]:
if colors is None:
return list(distinctColors(max(count, 1)))
- if isinstance(colors, (int, float)) or (len(colors) in (3, 4) and all(isinstance(c, (int, float)) for c in colors)):
- return [colors] * max(count, 1) # type: ignore[list-item]
- palette = list(colors)
+ if is_single_color(colors):
+ return [as_color(colors)] * max(count, 1)
+ palette: list[Color] = [as_color(c) for c in colors] # type: ignore[union-attr]
if len(palette) != count:
raise ValueError(f"colors must have one entry per item, got {len(palette)} for {count} items")
return palette
@@ -638,7 +639,7 @@ def drawTextBlock(
ValueError: If ``img`` is not 8-bit, ``alpha`` is outside ``[0, 1]``, ``padding`` is negative, or
``fontScale`` / ``lineSpacing`` is not positive.
"""
- _check_uint8("img", img)
+ check_uint8("img", img)
_check_unit("alpha", alpha)
check_finite("fontScale", fontScale, positive=True)
check_finite("lineSpacing", lineSpacing, positive=True)
@@ -751,7 +752,7 @@ def drawLegend(
ValueError: If ``colors`` has a different length than ``labels``, ``swatch`` is not positive, or see
:func:`drawTextBlock`.
"""
- _check_uint8("img", img)
+ check_uint8("img", img)
_check_unit("alpha", alpha)
if swatch < 1:
raise ValueError(f"swatch must be positive, got {swatch}")
@@ -836,8 +837,8 @@ def compareImages(
ValueError: If an image is not 8-bit, ``mode`` is unknown, ``split`` is outside ``[0, 1]``, ``gap`` is
negative or ``labels`` does not have two entries.
"""
- _check_uint8("a", a)
- _check_uint8("b", b)
+ check_uint8("a", a)
+ check_uint8("b", b)
if mode not in ("side", "vertical", "split", "blend", "diff"):
raise ValueError(f"mode must be 'side', 'vertical', 'split', 'blend' or 'diff', got {mode!r}")
_check_unit("split", split)
@@ -906,7 +907,7 @@ def labeledMontage(
fill = _bgr(color)
cells = []
for img, text in zip(images, labels, strict=True):
- _check_uint8("images", img)
+ check_uint8("images", img)
tile = toBGR(img)
if cellSize is not None:
tile = letterbox(tile, cellSize, color=fill)[0]
@@ -935,7 +936,7 @@ def blendImages(images: Sequence[np.ndarray], weights: Sequence[float] | None =
if len(images) == 0:
raise ValueError("images must not be empty")
for img in images:
- _check_uint8("images", img)
+ check_uint8("images", img)
if weights is None:
weights = [1.0] * len(images)
if len(weights) != len(images):
@@ -955,5 +956,6 @@ def blendImages(images: Sequence[np.ndarray], weights: Sequence[float] | None =
img = convert(img)
if img.shape[:2] != (height, width):
img = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)
- acc += img.astype(np.float32) * (float(w) / total)
+ # (h, w, 1) and (h, w) both count as one channel; cv.resize also drops a trailing 1.
+ acc += img.reshape(first.shape).astype(np.float32) * (float(w) / total)
return np.clip(np.rint(acc), 0, 255).astype(np.uint8)
diff --git a/cv2u/videoio/reader.py b/cv2u/videoio/reader.py
index 704c0f6..2def373 100644
--- a/cv2u/videoio/reader.py
+++ b/cv2u/videoio/reader.py
@@ -342,6 +342,7 @@ def __init__(self, source: VideoSource, maxWait: float = 5.0) -> None:
self._thread: threading.Thread | None = None
self._counter = FPSCounter()
self._ended = False
+ self._delivered = False
@property
def isRunning(self) -> bool:
@@ -373,6 +374,7 @@ def _run(self) -> None:
break
with self._lock:
self._frame = frame
+ self._delivered = False
self._counter.tick()
self._has_frame.set()
self._has_frame.set()
@@ -380,12 +382,18 @@ def _run(self) -> None:
def read(self) -> np.ndarray | None:
"""Return the latest frame, or ``None`` if none arrived within ``maxWait`` or the stream ended.
- Returns the same frame again when no new one arrived in the meantime. The thread is started if needed.
+ Returns the same frame again when no new one arrived in the meantime, as long as the source is still
+ running. Once the source has ended (:attr:`ended`), the last frame is returned once more if it has not been
+ read yet, then ``None`` forever, so a ``while (frame := stream.read()) is not None`` loop terminates on
+ a file. The thread is started if needed.
"""
self.start()
if not self._has_frame.wait(self.maxWait):
return None
with self._lock:
+ if self._ended and self._delivered:
+ return None
+ self._delivered = True
return self._frame
def stop(self) -> None:
diff --git a/tests/test_annotations.py b/tests/test_annotations.py
index bba0876..43d3a9d 100644
--- a/tests/test_annotations.py
+++ b/tests/test_annotations.py
@@ -108,7 +108,9 @@ def test_polygonsToMask_validation():
with pytest.raises(ValueError, match="polygons"):
polygonsToMask(np.zeros((2, 3)), (5, 5))
with pytest.raises(ValueError, match="polygons"):
- polygonsToMask([[[[1, 2]]]], (5, 5))
+ polygonsToMask([[[[[1, 2]]]]], (5, 5)) # 5-D: not a polygon list
+ with pytest.raises(ValueError, match="polygons"):
+ polygonsToMask([np.zeros((2, 2, 2))], (5, 5)) # (N, 2, 2) is neither (N, 2) nor (N, 1, 2)
assert polygonsToMask(np.zeros((3, 1, 2), np.int32), (5, 5)).shape == (5, 5) # one (N, 1, 2) contour
@@ -511,3 +513,47 @@ def test_flip_validation():
flipPolygons([], (1, 0), 1)
with pytest.raises(ValueError, match="flipCode"):
flipPolygons([], SIZE, 5)
+
+
+# --- regression: review findings ----------------------------------------------------------------------------------
+
+
+def test_drawPolygons_label_text_is_white_on_dark_boxes(canvas):
+ # A scalar 255 text color is expanded by OpenCV to (255, 0, 0): blue text on a BGR image.
+ quad = [(10, 20), (70, 20), (70, 50), (10, 50)]
+ drawPolygons(canvas, [quad], color=(0, 0, 0), labels=["dark"], thickness=1, lineType=cv2.LINE_8)
+ tag = canvas[:20, 10:50].reshape(-1, 3)
+ text = tag[tag.any(axis=1)]
+ assert len(text) > 0
+ assert np.all(text[:, 0] == text[:, 1]) and np.all(text[:, 1] == text[:, 2]) # gray levels, not blue
+ assert text.max() == 255
+ bgra = np.zeros((60, 80, 4), np.uint8)
+ drawPolygons(bgra, [quad], color=(0, 0, 0, 255), labels=["dark"], thickness=1, lineType=cv2.LINE_8)
+ text = bgra[:20, 10:50].reshape(-1, 4)
+ text = text[text[:, :3].any(axis=1)]
+ assert np.all(text[:, 0] == text[:, 2]) and np.all(text[:, 0] == text[:, 3]) and text.max() == 255
+
+
+def test_polygons_accepts_equal_length_contours_and_mixed_forms():
+ square = np.array([[[1, 1]], [[4, 1]], [[4, 4]], [[1, 4]]], np.int32) # (N, 1, 2) like cv.findContours
+ other = square + 3
+ mask = polygonsToMask([square, other], (10, 10)) # equal lengths: np.asarray would give a 4-D array
+ assert mask.shape == (10, 10) and mask[2, 2] == 255 and mask[6, 6] == 255 and mask[0, 0] == 0
+ mixed = [square, square.reshape(-1, 2) + 3, [(0, 8), (2, 8), (2, 9)]] # contour, (N, 2), point list
+ assert len(polygonsToBoxes(mixed)) == 3
+ ragged = [square, [(0, 8), (2, 8), (2, 9), (1, 9), (0, 9)]]
+ assert len(polygonsToBoxes(ragged)) == 2
+ assert polygonsToBoxes([square])[0].tolist() == [1, 1, 3, 3]
+
+
+def test_drawPolygons_numpy_array_is_one_color(canvas):
+ quad = [(10, 10), (50, 10), (50, 50), (10, 50)]
+ color = np.array([0, 0, 255], np.uint8) # e.g. a row of Clusters.centers
+ drawPolygons(canvas, [quad, quad], color=color, fill=True)
+ assert canvas[30, 30].tolist() == [0, 0, 255]
+ gray = np.zeros((60, 80), np.uint8)
+ drawPolygons(gray, [quad], color=np.uint8(200), fill=True)
+ assert gray[30, 30] == 200
+ centers = np.array([[255, 0, 0], [0, 255, 0]], np.uint8)
+ drawPolygons(canvas, [quad, [(60, 10), (70, 10), (70, 20)]], color=centers, fill=True)
+ assert canvas[30, 30].tolist() == [255, 0, 0]
diff --git a/tests/test_calib3d.py b/tests/test_calib3d.py
index df94e64..10cd286 100644
--- a/tests/test_calib3d.py
+++ b/tests/test_calib3d.py
@@ -158,7 +158,11 @@ def test_save_load_roundtrip(tmp_path, calib: CameraCalibration) -> None: # typ
assert np.allclose(loaded.distCoeffs, calib.distCoeffs) and loaded.distCoeffs.shape == calib.distCoeffs.shape
assert loaded.imageSize == calib.imageSize and loaded.rms == calib.rms
assert len(loaded.rvecs) == 5 and np.allclose(loaded.tvecs[2], calib.tvecs[2])
- assert set(json.loads(path.read_text("utf-8"))) >= {"cameraMatrix", "distCoeffs", "imageSize", "rms"}
+ assert loaded.usedViews == calib.usedViews == (0, 1, 2, 3, 4)
+ assert set(json.loads(path.read_text("utf-8"))) >= {"cameraMatrix", "distCoeffs", "imageSize", "rms", "usedViews"}
+ old = {k: v for k, v in json.loads(path.read_text("utf-8")).items() if k != "usedViews"}
+ (tmp_path / "old.json").write_text(json.dumps(old), "utf-8")
+ assert loadCalibration(tmp_path / "old.json").usedViews == () # files from before the field existed
def test_load_errors(tmp_path) -> None: # type: ignore[no-untyped-def]
@@ -168,3 +172,22 @@ def test_load_errors(tmp_path) -> None: # type: ignore[no-untyped-def]
loadCalibration(bad)
with pytest.raises(OSError):
loadCalibration(tmp_path / "missing.json")
+
+
+def test_calibrate_skipped_views_are_listed_in_usedViews(views: list[np.ndarray]) -> None:
+ blank = np.full_like(views[0], 255)
+ mixed = [views[0], blank, views[1], views[2], blank, views[3]]
+ calib = calibrateCameraEx(mixed, PATTERN, SQUARE)
+ assert calib.usedViews == (0, 2, 3, 5)
+ assert len(calib.rvecs) == len(calib.tvecs) == 4
+ corners = [findChessboardEx(v, PATTERN) for v in mixed]
+ assert corners[1] is None and corners[4] is None
+ full = reprojectionErrors(calib, PATTERN, SQUARE, corners) # one entry per original view, None included
+ used = reprojectionErrors(calib, PATTERN, SQUARE, [c for c in corners if c is not None]) # per used view
+ assert full.shape == (4,) and np.allclose(full, used)
+ with pytest.raises(ValueError, match="cornersList"):
+ reprojectionErrors(calib, PATTERN, SQUARE, corners[:5])
+ with pytest.raises(ValueError, match="None"):
+ reprojectionErrors(calib, PATTERN, SQUARE, [corners[0], None, corners[2], corners[3]])
+ from_corners = calibrateCameraEx([c for c in corners if c is not None], PATTERN, SQUARE, imageSize=SIZE)
+ assert from_corners.usedViews == (0, 1, 2, 3)
diff --git a/tests/test_dnn.py b/tests/test_dnn.py
index ade468d..92479f3 100644
--- a/tests/test_dnn.py
+++ b/tests/test_dnn.py
@@ -449,3 +449,18 @@ def test_loadModel_without_dnn_module(tmp_path, monkeypatch):
model.write_bytes(b"x")
with pytest.raises(RuntimeError, match=r"cv2.dnn"):
loadModel(model)
+
+
+def test_loadModel_reads_the_file_only_for_buffer_formats(tmp_path, monkeypatch):
+ read = []
+ monkeypatch.setattr(np, "fromfile", lambda path, dtype=None: read.append(str(path)) or np.zeros(1, np.uint8))
+ monkeypatch.setattr(cv2.dnn, "readNet", lambda *args: object())
+ monkeypatch.setattr(cv2.dnn, "readNetFromONNX", lambda buffer: object(), raising=False)
+ weights = tmp_path / "m.caffemodel"
+ weights.write_bytes(b"x" * 10)
+ loadModel(weights)
+ assert read == [] # not loaded into memory: OpenCV opens the path itself
+ onnx = tmp_path / "m.onnx"
+ onnx.write_bytes(b"x")
+ loadModel(onnx)
+ assert read == [str(onnx)]
diff --git a/tests/test_meta.py b/tests/test_meta.py
index 24fbc32..eb17bc4 100644
--- a/tests/test_meta.py
+++ b/tests/test_meta.py
@@ -220,3 +220,25 @@ def test_convert_errors(tmp_path):
assert not convertImageFormat(tmp_path / "missing.png", tmp_path / "x.png")
with pytest.raises(ValueError, match="extension"):
convertImageFormat(_save(tmp_path / "s.png", _image()), tmp_path / "noext")
+
+
+def test_convertImageFormat_scales_16bit_and_float_to_8bit_for_8bit_formats(tmp_path):
+ src16 = tmp_path / "deep.png"
+ assert cv2.imwrite(str(src16), np.full((8, 8, 3), 40000, np.uint16))
+ assert convertImageFormat(src16, tmp_path / "deep.jpg", quality=100)
+ out = imreadEx(tmp_path / "deep.jpg", cv2.IMREAD_UNCHANGED)
+ assert out.dtype == np.uint8 and abs(int(out[4, 4, 0]) - 156) <= 2 # 40000 / 257, not saturated to 255
+ assert convertImageFormat(src16, tmp_path / "deep.bmp")
+ assert imreadEx(tmp_path / "deep.bmp", cv2.IMREAD_UNCHANGED)[4, 4, 0] == 156
+ assert convertImageFormat(src16, tmp_path / "kept.png")
+ assert imreadEx(tmp_path / "kept.png", cv2.IMREAD_UNCHANGED).dtype == np.uint16 # PNG keeps 16-bit
+ assert convertImageFormat(src16, tmp_path / "kept.tif")
+ assert imreadEx(tmp_path / "kept.tif", cv2.IMREAD_UNCHANGED).dtype == np.uint16
+
+ srcf = tmp_path / "float.tif"
+ assert cv2.imwrite(str(srcf), np.full((8, 8), 0.5, np.float32))
+ assert convertImageFormat(srcf, tmp_path / "float.jpg", quality=100)
+ out = imreadEx(tmp_path / "float.jpg", cv2.IMREAD_UNCHANGED)
+ assert out.dtype == np.uint8 and abs(int(out[4, 4]) - 128) <= 2
+ assert convertImageFormat(srcf, tmp_path / "float.pfm")
+ assert imreadEx(tmp_path / "float.pfm", cv2.IMREAD_UNCHANGED).dtype == np.float32 # PFM keeps floats
diff --git a/tests/test_stats.py b/tests/test_stats.py
index eb5d500..6dd49f0 100644
--- a/tests/test_stats.py
+++ b/tests/test_stats.py
@@ -343,3 +343,18 @@ def test_bad_images(fn):
fn(np.zeros((0, 4), np.uint8))
with pytest.raises(ValueError):
fn(np.zeros((4, 4, 2), np.uint8))
+
+
+@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.float32])
+def test_imageStats_matches_the_single_metric_functions(photo, dtype):
+ from cv2u.imgproc.quality import sharpnessScore
+
+ img = photo.astype(dtype) * (257 if dtype == np.uint16 else 1 / 255 if dtype == np.float32 else 1)
+ s = imageStats(img)
+ assert s.brightness == brightnessScore(img)
+ assert s.contrast == contrastScore(img)
+ assert s.sharpness == sharpnessScore(img)
+ assert s.entropy == entropy(img)
+ assert s.isGray == isGrayscale(img)
+ gray = imageStats(photo[..., 1])
+ assert gray.isGray and gray.entropy == entropy(photo[..., 1]) and gray.sharpness == sharpnessScore(photo[..., 1])
diff --git a/tests/test_validation.py b/tests/test_validation.py
index e48d49a..dac887c 100644
--- a/tests/test_validation.py
+++ b/tests/test_validation.py
@@ -366,3 +366,59 @@ def read(self, n=-1):
monkeypatch.setattr(urlread_module, "urlopen", lambda request, timeout=None: Response())
with pytest.raises(ValueError, match="maxBytes"):
cv.imreadUrl("https://example.invalid/big.png", maxBytes=1000)
+
+
+# --- shared helpers in cv2u._validate -------------------------------------------------------------------------------
+
+
+def test_check_size_accepts_positive_sizes_and_names_the_argument():
+ from cv2u._validate import check_size
+
+ assert check_size("size", (3, 4)) == (3, 4)
+ assert check_size("size", [2.0, 5.0]) == (2, 5)
+ for bad in [(0, 4), (3, -1), (NAN, 4), (3, INF), (3,)]:
+ with pytest.raises(ValueError, match="patch"):
+ check_size("patch", bad)
+
+
+def test_check_uint8_rejects_other_depths_empty_and_two_channel_images():
+ from cv2u._validate import check_uint8
+
+ assert check_uint8("src", IMG) == 3 and check_uint8("src", GRAY) == 1
+ with pytest.raises(ValueError, match=r"src.*uint8"):
+ check_uint8("src", IMG.astype(np.float32))
+ with pytest.raises(ValueError, match=r"src.*empty"):
+ check_uint8("src", EMPTY)
+ with pytest.raises(ValueError, match=r"src.*channels"):
+ check_uint8("src", np.zeros((4, 4, 2), np.uint8))
+
+
+def test_is_single_color_and_as_color():
+ from cv2u._validate import as_color, is_single_color
+
+ assert (
+ is_single_color(200)
+ and is_single_color(1.5)
+ and is_single_color(np.uint8(3))
+ and is_single_color(np.float32(1))
+ )
+ assert is_single_color((0, 0, 255)) and is_single_color([0, 0, 255, 255]) and is_single_color([7])
+ assert is_single_color(np.array([0, 0, 255], np.uint8)) and is_single_color(np.array([0.5, 0.5, 0.5]))
+ assert is_single_color((np.uint8(1), np.uint8(2), np.uint8(3)))
+ assert not is_single_color([(0, 0, 255), (255, 0, 0)])
+ assert not is_single_color(np.array([[0, 0, 255], [255, 0, 0]], np.uint8))
+ assert not is_single_color([200, 100]) # two gray levels, no image has 2 channels
+ assert not is_single_color("red") and not is_single_color(True) and not is_single_color(None)
+ assert not is_single_color([]) and not is_single_color([[1, 2, 3]])
+ assert as_color(np.array([0, 0, 255], np.uint8)) == (0.0, 0.0, 255.0)
+ assert as_color(np.uint8(9)) == 9.0 and as_color(3) == 3.0 and as_color([1, 2, 3]) == (1.0, 2.0, 3.0)
+
+
+def test_drawBoxes_numpy_color_is_one_color():
+ img = IMG.copy()
+ cv.drawBoxes(img, [(5, 5, 10, 10), (20, 20, 10, 10)], colors=np.array([0, 0, 255], np.uint8), thickness=1)
+ assert img[5, 10].tolist() == [0, 0, 255] and img[20, 25].tolist() == [0, 0, 255]
+ img = IMG.copy()
+ cv.drawBoxes(img, [(5, 5, 10, 10), (20, 20, 10, 10)], colors=np.array([[255, 0, 0], [0, 255, 0]], np.uint8))
+ assert img[5, 10].tolist() == [255, 0, 0] and img[20, 25].tolist() == [0, 255, 0]
+ cv.drawBoxes(img, [(5, 5, 10, 10)], labels=["a"], colors=np.uint8(255))
diff --git a/tests/test_videoio_reader.py b/tests/test_videoio_reader.py
index 39773c6..da23164 100644
--- a/tests/test_videoio_reader.py
+++ b/tests/test_videoio_reader.py
@@ -186,18 +186,34 @@ def test_CameraStream_on_a_file(video):
assert stream.fps >= 0
-def test_CameraStream_ends_and_keeps_last_frame(video):
+def test_CameraStream_ends_and_delivers_last_frame_once(video):
stream = CameraStream(video, maxWait=2.0).start()
try:
stream._thread.join(timeout=5) # the file is short: the thread finishes
assert stream.ended
last = stream.read()
assert last is not None and _bar_width(last) == 64
+ assert stream.read() is None # the docstring promise: None once the stream ended
+ assert stream.read() is None
finally:
stream.stop()
stream.stop() # idempotent
+def test_CameraStream_read_loop_terminates_on_a_file(video):
+ import time
+
+ deadline = time.monotonic() + 10
+ last = None
+ count = 0
+ with CameraStream(video, maxWait=2.0) as stream:
+ while (frame := stream.read()) is not None: # the same frame may repeat while the thread still runs
+ last, count = frame, count + 1
+ if time.monotonic() > deadline:
+ pytest.fail("read() never returned None after the file ended")
+ assert count >= 1 and _bar_width(last) == 64
+
+
def test_CameraStream_missing(tmp_path):
with pytest.raises(OSError):
CameraStream(tmp_path / "missing.avi")
diff --git a/tests/test_visualize.py b/tests/test_visualize.py
index 5171ea6..b21b1c6 100644
--- a/tests/test_visualize.py
+++ b/tests/test_visualize.py
@@ -407,3 +407,28 @@ def test_blendImages() -> None:
blendImages([a, b], weights=[1, -1])
with pytest.raises(ValueError, match="weights"):
blendImages([a, b], weights=[0, 0])
+
+
+def test_palette_numpy_array_is_one_color() -> None:
+ assert visualize._palette(np.array([0, 0, 255], np.uint8), 3) == [(0.0, 0.0, 255.0)] * 3
+ assert visualize._palette(np.float32(200), 2) == [200.0, 200.0]
+ assert visualize._palette(np.array([[255, 0, 0], [0, 255, 0]], np.uint8), 2) == [
+ (255.0, 0.0, 0.0),
+ (0.0, 255.0, 0.0),
+ ]
+ assert visualize._palette([200, 100], 2) == [200.0, 100.0] # two gray levels, not one 2-channel color
+ img = bgr()
+ boxes = [((40, 30), (20, 10), 0.0), ((40, 30), (20, 10), 90.0)]
+ drawRotatedBoxes(img, boxes, colors=np.array([0, 0, 255], np.uint8), thickness=1)
+ drawn = img.reshape(-1, 3)[img.reshape(-1, 3).any(axis=1)]
+ assert len(drawn) > 0 and not drawn[:, :2].any() and drawn[:, 2].max() > 200 # red only (anti-aliased)
+
+
+def test_blendImages_single_channel_3d_inputs() -> None:
+ a = np.full((20, 30, 1), 0, np.uint8)
+ b = np.full((20, 30), 200, np.uint8)
+ assert blendImages([a, b]).shape == (20, 30, 1) and np.all(blendImages([a, b]) == 100)
+ assert blendImages([b, a]).shape == (20, 30) and np.all(blendImages([b, a]) == 100)
+ assert np.all(blendImages([a, a[:10, :10]]) == 0) # (h, w, 1) resized: cv.resize drops the trailing 1
+ c = bgr(20, 30, 200)
+ assert blendImages([a, c]).shape == (20, 30, 1) and np.all(blendImages([a, c]) == 100)