imgcodecs: scale binary PNM samples for non-full maxval 🤖🤖🤖 (#31209)

Apply the existing lookup table to binary 8-bit PGM/PPM samples when maxval is below 255, clamping out-of-range values as the ASCII path already does. The maxval-255 fast path and 16-bit behavior are unchanged.

Add generated PGM and PPM cases comparing ASCII and binary decoding across several maxvals and read modes; no external image data is needed.
This commit is contained in:
NIKHILA
2026-12-02 15:21:30 +05:30
committed by GitHub
parent 573d22b961
commit 30ef29162c
2 changed files with 57 additions and 0 deletions

View File

@@ -299,6 +299,11 @@ bool PxMDecoder::readData( Mat& img )
else
{
m_strm.getBytes( src, src_pitch );
if( bit_depth == 8 && m_maxval < 255 )
{
for (int x = 0; x < width3; x++)
src[x] = gray_palette[std::min<int>(src[x], m_maxval)];
}
if( bit_depth == 16 && !isBigEndian() )
{
for (int x = 0; x < width3; x++)

View File

@@ -712,6 +712,58 @@ TEST(Imgcodecs, imdecode_user_buffer)
EXPECT_TRUE(result.empty());
}
#ifdef HAVE_IMGCODEC_PXM
typedef testing::TestWithParam<tuple<int, int, int> > Imgcodecs_Pxm_Maxval;
TEST_P(Imgcodecs_Pxm_Maxval, binary_matches_ascii_maxval)
{
const int channels = get<0>(GetParam());
const int maxval = get<1>(GetParam());
const int mode = get<2>(GetParam());
// The final sample exceeds maxval where an 8-bit value permits it.
const int samples[] = {0, maxval / 2, maxval, std::min(maxval + 1, 255)};
const uchar midpoint = maxval == 1 ? 0 : maxval == 15 ? 119 : 127;
const uchar expected[] = {0, midpoint, 255, 255};
const std::string header = cv::format("\n4 1\n%d\n", maxval);
std::string ascii = std::string(channels == 1 ? "P2" : "P3") + header;
const std::string binaryHeader = std::string(channels == 1 ? "P5" : "P6") + header;
std::vector<uchar> binary(binaryHeader.begin(), binaryHeader.end());
for (int x = 0; x < 4; ++x)
{
for (int c = 0; c < channels; ++c)
{
ascii += cv::format("%d ", samples[x]);
binary.push_back(static_cast<uchar>(samples[x]));
}
}
const std::vector<uchar> plain(ascii.begin(), ascii.end());
const Mat decoded[] = {imdecode(plain, mode), imdecode(binary, mode)};
const int outputChannels = mode == IMREAD_UNCHANGED ? channels :
mode == IMREAD_GRAYSCALE ? 1 : 3;
for (int encoding = 0; encoding < 2; ++encoding)
{
SCOPED_TRACE(encoding == 0 ? "ASCII" : "binary");
const Mat& image = decoded[encoding];
ASSERT_FALSE(image.empty());
ASSERT_EQ(CV_MAKETYPE(CV_8U, outputChannels), image.type());
ASSERT_EQ(Size(4, 1), image.size());
for (int x = 0; x < 4; ++x)
for (int c = 0; c < outputChannels; ++c)
EXPECT_EQ(expected[x], image.ptr<uchar>(0)[x * outputChannels + c])
<< "x=" << x << " channel=" << c;
}
}
INSTANTIATE_TEST_CASE_P(Encodings, Imgcodecs_Pxm_Maxval,
testing::Combine(testing::Values(1, 3), testing::Values(1, 15, 100, 255),
testing::Values(IMREAD_UNCHANGED, IMREAD_GRAYSCALE,
IMREAD_COLOR, IMREAD_COLOR_RGB)));
#endif
}} // namespace
#if defined(HAVE_OPENEXR) && defined(OPENCV_IMGCODECS_ENABLE_OPENEXR_TESTS)