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.
This commit is contained in:
Shiven Solanki
2026-10-31 01:51:46 +08:00
parent d195a5ad7e
commit f2bed79fc3
2 changed files with 19 additions and 2 deletions

View File

@@ -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");

View File

@@ -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<uchar> 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.