From f2bed79fc3673dab7e145579b95f6e161bb211b2 Mon Sep 17 00:00:00 2001 From: Shiven Solanki Date: Sat, 31 Oct 2026 01:51:46 +0800 Subject: [PATCH] imgcodecs: read 16-bit and 4-channel PAM files without TUPLTYPE PAM files written by imwrite without IMWRITE_PAM_TUPLETYPE have no TUPLTYPE line. readHeader only guessed the format for 8-bit images with 1 or 3 channels and threw for everything else, so 16-bit and 4-channel images written by OpenCV could not be read back. Leave the format unset in that case: readData already handles it with the default layout. Add an Imgcodecs_Pam regression test. --- modules/imgcodecs/src/grfmt_pam.cpp | 2 -- modules/imgcodecs/test/test_grfmt.cpp | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/modules/imgcodecs/src/grfmt_pam.cpp b/modules/imgcodecs/src/grfmt_pam.cpp index abc48cd1ad..b4f3b03ec1 100644 --- a/modules/imgcodecs/src/grfmt_pam.cpp +++ b/modules/imgcodecs/src/grfmt_pam.cpp @@ -508,8 +508,6 @@ bool PAMDecoder::readHeader() selected_fmt = IMWRITE_PAM_FORMAT_GRAYSCALE; else if (m_channels == 3 && m_maxval < 256) selected_fmt = IMWRITE_PAM_FORMAT_RGB; - else - CV_Error(Error::StsError, "Can't determine selected_fmt (IMWRITE_PAM_FORMAT_NULL)"); } CV_CheckDepth(m_sampledepth, m_sampledepth == CV_8U || m_sampledepth == CV_16U, ""); CV_Check(m_channels, m_channels >= 1 && m_channels <= 4, "Unsupported number of channels"); diff --git a/modules/imgcodecs/test/test_grfmt.cpp b/modules/imgcodecs/test/test_grfmt.cpp index 352be3f37d..936f9934f3 100644 --- a/modules/imgcodecs/test/test_grfmt.cpp +++ b/modules/imgcodecs/test/test_grfmt.cpp @@ -565,6 +565,25 @@ TEST(Imgcodecs_Pam, read_write) remove(writefile_no_param.c_str()); } +// PAM files written without IMWRITE_PAM_TUPLETYPE have no TUPLTYPE line; +// the reader must still accept 4-channel and 16-bit ones +TEST(Imgcodecs_Pam, read_write_without_tupltype) +{ + for (int type : {CV_8UC4, CV_16UC1, CV_16UC3, CV_16UC4}) + { + Mat img(4, 5, type); + randu(img, 0, CV_MAT_DEPTH(type) == CV_8U ? 256 : 65536); + + std::vector buf; + ASSERT_TRUE(imencode(".pam", img, buf)) << typeToString(type); + Mat decoded = imdecode(buf, IMREAD_UNCHANGED); + + ASSERT_FALSE(decoded.empty()) << typeToString(type); + EXPECT_EQ(type, decoded.type()); + EXPECT_EQ(0, cvtest::norm(img, decoded, NORM_INF)) << typeToString(type); + } +} + // Regression test: a 2-channel (GRAYSCALE_ALPHA) PAM decoded as single channel // used to overflow the output row in basic_conversion() (3 bytes written per // source pixel into a 1-channel row). Verify it decodes safely and correctly.