diff --git a/modules/core/CMakeLists.txt b/modules/core/CMakeLists.txt index b0a1e8ed06..8b25211f76 100644 --- a/modules/core/CMakeLists.txt +++ b/modules/core/CMakeLists.txt @@ -11,6 +11,7 @@ ocv_add_dispatched_file(has_non_zero SSE2 AVX2 LASX ) ocv_add_dispatched_file(matmul SSE2 SSE4_1 AVX2 AVX512_SKX NEON_DOTPROD LASX) ocv_add_dispatched_file(mean SSE2 AVX2 AVX512_SKX AVX512_ICL LASX) ocv_add_dispatched_file(merge SSE2 AVX2 LASX) +ocv_add_dispatched_file(channel_permutation SSE4_1 AVX2 LASX) ocv_add_dispatched_file(minmax SSE2 SSE4_1 AVX2 AVX512_SKX AVX512_ICL VSX3 LASX) ocv_add_dispatched_file(nan_mask SSE2 AVX2 LASX) ocv_add_dispatched_file(split SSE2 AVX2 LASX) diff --git a/modules/core/perf/perf_mix_channels.cpp b/modules/core/perf/perf_mix_channels.cpp new file mode 100644 index 0000000000..c76b85fe67 --- /dev/null +++ b/modules/core/perf/perf_mix_channels.cpp @@ -0,0 +1,65 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#include "perf_precomp.hpp" + +namespace opencv_test +{ +using namespace perf; + +typedef TestBaseWithParam> MixChannelsPermutation; + +PERF_TEST_P(MixChannelsPermutation, interleaved, + testing::Combine(testing::Values(Size(256, 256), Size(512, 512), Size(1024, 1024)), + testing::Values(CV_8UC2, CV_8UC3, CV_8UC4, CV_16UC2, CV_16UC3, CV_16UC4, + CV_32FC2, CV_32FC3, CV_32FC4), + testing::Bool(), testing::Bool())) +{ + const Size size = get<0>(GetParam()); + const int type = get<1>(GetParam()); + const bool roi = get<2>(GetParam()); + const bool swapOuter = get<3>(GetParam()); + const Rect region(roi ? 1 : 0, roi ? 1 : 0, size.width, size.height); + const Size storage(region.x + size.width, region.y + size.height); + Mat source(storage, type); + Mat destination(storage, type); + const Mat src = source(region); + Mat dst = destination(region); + declare.in(source, WARMUP_RNG).out(destination); + + const int rgb[] = {2, 0, swapOuter ? 1 : 0, 1, swapOuter ? 0 : 1, 2, 3, 3}; + const int twoChannels[] = {swapOuter ? 1 : 0, 0, swapOuter ? 0 : 1, 1}; + const int* fromTo = src.channels() == 2 ? twoChannels : rgb; + TEST_CYCLE() mixChannels(&src, 1, &dst, 1, fromTo, src.channels()); + SANITY_CHECK_NOTHING(); +} + +typedef TestBaseWithParam> MixChannelsWidePermutation; + +PERF_TEST_P(MixChannelsWidePermutation, interleaved, + testing::Combine(testing::Values(CV_8UC(5), CV_8UC(8), CV_8UC(12), CV_8UC(16), + CV_32FC(32), CV_32FC(64), CV_32FC(CV_CN_MAX), + CV_32SC(64), CV_32UC(64)), + testing::Bool())) +{ + const int type = get<0>(GetParam()); + const bool roi = get<1>(GetParam()); + const Rect region(roi ? 1 : 0, 0, 512, 512); + Mat source(region.height, region.x + region.width, type); + Mat destination(source.size(), type); + const Mat src = source(region); + Mat dst = destination(region); + declare.in(source, WARMUP_RNG).out(destination); + + std::vector fromTo; + for (int channel = 0; channel < src.channels(); ++channel) + { + fromTo.push_back(src.channels() - 1 - channel); + fromTo.push_back(channel); + } + TEST_CYCLE() mixChannels(&src, 1, &dst, 1, fromTo.data(), src.channels()); + SANITY_CHECK_NOTHING(); +} + +} // namespace opencv_test diff --git a/modules/core/src/channel_permutation.simd.hpp b/modules/core/src/channel_permutation.simd.hpp new file mode 100644 index 0000000000..1869ed7b0d --- /dev/null +++ b/modules/core/src/channel_permutation.simd.hpp @@ -0,0 +1,268 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#include "precomp.hpp" + +#include + +namespace cv { +CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN + +bool permuteByteChannels(NAryMatIterator& it, const int* order, int channels); +bool permuteSmallChannels(NAryMatIterator& it, const int* order, int channels, size_t elemSize); +bool permuteWideChannels(NAryMatIterator& it, const int* order, int channels); + +#ifndef CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY +#if CV_NEON && (defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC)) +#define CV_CHANNEL_PERMUTATION_NEON_AARCH64 1 +#else +#define CV_CHANNEL_PERMUTATION_NEON_AARCH64 0 +#endif + +#if CV_SSSE3 || CV_CHANNEL_PERMUTATION_NEON_AARCH64 +namespace { + +constexpr int vectorBytes = 16; + +struct ByteShuffle +{ + int offset; +#if CV_SSSE3 + v_uint8x16 masks[4]; +#else + v_uint8x16 mask; +#endif +}; + +template +inline v_uint8x16 shuffleBytes(const uchar* src, const ByteShuffle& shuffle) +{ +#if CV_SSSE3 + __m128i result = _mm_shuffle_epi8(v_load(src).val, shuffle.masks[0].val); + for (int index = 1; index < vectors; ++index) + result = _mm_or_si128(result, _mm_shuffle_epi8(v_load(src + index * vectorBytes).val, + shuffle.masks[index].val)); + return v_uint8x16(result); +#elif CV_CHANNEL_PERMUTATION_NEON_AARCH64 + if constexpr (vectors == 1) + return v_uint8x16(vqtbl1q_u8(vld1q_u8(src), shuffle.mask.val)); + else if constexpr (vectors == 2) + { + const uint8x16x2_t table = {{vld1q_u8(src), vld1q_u8(src + vectorBytes)}}; + return v_uint8x16(vqtbl2q_u8(table, shuffle.mask.val)); + } + else if constexpr (vectors == 3) + { + const uint8x16x3_t table = {{vld1q_u8(src), vld1q_u8(src + vectorBytes), + vld1q_u8(src + 2 * vectorBytes)}}; + return v_uint8x16(vqtbl3q_u8(table, shuffle.mask.val)); + } + else + { + const uint8x16x4_t table = {{vld1q_u8(src), vld1q_u8(src + vectorBytes), + vld1q_u8(src + 2 * vectorBytes), vld1q_u8(src + 3 * vectorBytes)}}; + return v_uint8x16(vqtbl4q_u8(table, shuffle.mask.val)); + } +#endif +} + +template +void shufflePlanes(NAryMatIterator& it, const int* order, int channels, + const ByteShuffle* shuffles, int blockBytes) +{ + const size_t rowBytes = it.size * channels; + const size_t bulk = rowBytes / blockBytes * blockBytes; + for (size_t plane = 0; plane < it.nplanes; ++plane, ++it) + { + const uchar* src = it.ptrs[0]; + uchar* dst = it.ptrs[1]; + if (vectors == 1 && blockBytes == vectorBytes) + { + for (size_t out = 0; out < bulk; out += vectorBytes) + v_store(dst + out, shuffleBytes<1>(src + out, shuffles[0])); + } + else + { + for (size_t out = 0; out < bulk; out += blockBytes) + for (int step = 0; step < blockBytes / vectorBytes; ++step) + v_store(dst + out + step * vectorBytes, + shuffleBytes(src + out + shuffles[step].offset, shuffles[step])); + } + for (size_t out = bulk; out < rowBytes; out += channels) + for (int channel = 0; channel < channels; ++channel) + dst[out + channel] = src[out + order[channel]]; + } +} + +} // namespace +#endif + +template +void copyPermutedPixels(const T* src, T* dst, int pixels, const int* order, int channels) +{ + for (int pixel = 0; pixel < pixels; ++pixel, src += channels, dst += channels) + for (int channel = 0; channel < channels; ++channel) + dst[channel] = src[order[channel]]; +} + +#if CV_SIMD || CV_SIMD_SCALABLE +template +void permuteChannels(NAryMatIterator& it, const int* order) +{ + const int lanes = VTraits::vlanes(); + const int pixels = static_cast(it.size); + VecT a, b, c, d; + const VecT* vectors[] = {&a, &b, &c, &d}; + const VecT& first = swapRB ? c : *vectors[order[0]]; + const VecT& second = swapRB ? b : *vectors[order[1]]; + const VecT& third = swapRB ? a : *vectors[channels == 2 ? 0 : order[2]]; + const VecT& fourth = swapRB ? d : *vectors[channels == 4 ? order[3] : 0]; + + for (size_t plane = 0; plane < it.nplanes; ++plane, ++it) + { + const T* src = reinterpret_cast(it.ptrs[0]); + T* dst = reinterpret_cast(it.ptrs[1]); + int pixel = 0; + for (; pixel <= pixels - lanes; pixel += lanes, src += lanes * channels, dst += lanes * channels) + { + if constexpr (channels == 2) + { + v_load_deinterleave(src, a, b); + v_store_interleave(dst, b, a); + } + else if constexpr (channels == 3) + { + v_load_deinterleave(src, a, b, c); + v_store_interleave(dst, first, second, third); + } + else + { + v_load_deinterleave(src, a, b, c, d); + v_store_interleave(dst, first, second, third, fourth); + } + } + copyPermutedPixels(src, dst, pixels - pixel, order, channels); + } + vx_cleanup(); +} + +template +void permuteChannels(NAryMatIterator& it, const int* order, int channels) +{ + const bool swapRB = order[0] == 2 && order[1] == 1; + if (channels == 2) + permuteChannels(it, order); + else if (channels == 3) + { + if (swapRB) + permuteChannels(it, order); + else + permuteChannels(it, order); + } + else if (swapRB && order[3] == 3) + permuteChannels(it, order); + else + permuteChannels(it, order); +} +#endif + +bool permuteSmallChannels(NAryMatIterator& it, const int* order, int channels, size_t elemSize) +{ +#if CV_SIMD || CV_SIMD_SCALABLE + switch (elemSize) + { + case 1: permuteChannels(it, order, channels); return true; + case 2: permuteChannels(it, order, channels); return true; + case 4: permuteChannels(it, order, channels); return true; + default: return false; + } +#else + CV_UNUSED(it); + CV_UNUSED(order); + CV_UNUSED(channels); + CV_UNUSED(elemSize); + return false; +#endif +} + +bool permuteWideChannels(NAryMatIterator& it, const int* order, int channels) +{ + for (size_t plane = 0; plane < it.nplanes; ++plane, ++it) + copyPermutedPixels(reinterpret_cast(it.ptrs[0]), reinterpret_cast(it.ptrs[1]), + static_cast(it.size), order, channels); + return true; +} + +bool permuteByteChannels(NAryMatIterator& it, const int* order, int channels) +{ +#if CV_SSSE3 || CV_CHANNEL_PERMUTATION_NEON_AARCH64 +#if CV_CHANNEL_PERMUTATION_NEON_AARCH64 + if (channels >= 9 && channels <= 12) + return false; +#endif + + // Align each block to both a pixel boundary and a vector boundary. + const int blockBytes = std::lcm(channels, vectorBytes); + const int steps = blockBytes / vectorBytes; + + int indices[vectorBytes][vectorBytes]; + int bases[vectorBytes]; + int vectors = 1; + for (int step = 0; step < steps; ++step) + { + for (int lane = 0; lane < vectorBytes; ++lane) + { + const int out = step * vectorBytes + lane; + indices[step][lane] = out / channels * channels + order[out % channels]; + } + const auto range = std::minmax_element(indices[step], indices[step] + vectorBytes); + bases[step] = *range.first / vectorBytes * vectorBytes; + vectors = std::max(vectors, (*range.second - bases[step]) / vectorBytes + 1); + } + + CV_DbgAssert(vectors <= 4); + ByteShuffle shuffles[vectorBytes]; + for (int step = 0; step < steps; ++step) + { + ByteShuffle& shuffle = shuffles[step]; + shuffle.offset = std::min(bases[step], blockBytes - vectors * vectorBytes); +#if CV_SSSE3 + for (int index = 0; index < vectors; ++index) + { + uchar mask[vectorBytes]; + for (int lane = 0; lane < vectorBytes; ++lane) + { + const int local = indices[step][lane] - shuffle.offset - index * vectorBytes; + mask[lane] = static_cast(local >= 0 && local < vectorBytes ? local : 255); + } + shuffle.masks[index] = v_load(mask); + } +#else + uchar mask[vectorBytes]; + for (int lane = 0; lane < vectorBytes; ++lane) + mask[lane] = static_cast(indices[step][lane] - shuffle.offset); + shuffle.mask = v_load(mask); +#endif + } + + switch (vectors) + { + case 1: shufflePlanes<1>(it, order, channels, shuffles, blockBytes); return true; + case 2: shufflePlanes<2>(it, order, channels, shuffles, blockBytes); return true; + case 3: shufflePlanes<3>(it, order, channels, shuffles, blockBytes); return true; + case 4: shufflePlanes<4>(it, order, channels, shuffles, blockBytes); return true; + default: return false; + } +#else + CV_UNUSED(it); + CV_UNUSED(order); + CV_UNUSED(channels); + return false; +#endif +} +#undef CV_CHANNEL_PERMUTATION_NEON_AARCH64 +#endif + +CV_CPU_OPTIMIZATION_NAMESPACE_END +} // namespace cv diff --git a/modules/core/src/channels.cpp b/modules/core/src/channels.cpp index e88d34a47e..604fae0693 100644 --- a/modules/core/src/channels.cpp +++ b/modules/core/src/channels.cpp @@ -6,6 +6,11 @@ #include "precomp.hpp" #include "opencl_kernels_core.hpp" #include "convert.hpp" +#include "channel_permutation.simd.hpp" +#include "channel_permutation.simd_declarations.hpp" + +#include +#include /****************************************************************************************\ * Generalized split/merge: mixing channels * @@ -91,6 +96,64 @@ static MixChannelsFunc getMixchFunc(int depth) return mixchTab[depth]; } +static bool tryPermuteChannels(const Mat& src, const Mat& dst, const int* fromTo, size_t npairs, + NAryMatIterator& it) +{ + const int channels = src.channels(); + if (npairs != static_cast(channels) || src.type() != dst.type() || src.empty() || dst.empty()) + return false; + + const size_t elemSize = src.elemSize1(); + const size_t pixels = it.size * it.nplanes; + const bool bytes = channels >= 5 && channels <= 16 && elemSize == 1 && it.size >= 16 && pixels >= 1024; + const bool wide32 = channels >= 32 && elemSize == 4 && pixels >= 65536; + const bool small = channels >= 2 && channels <= 4 && elemSize <= 4; + if (!(small || bytes || wide32)) + return false; + + // Preserve the existing write order for overlapping matrices. + const size_t planeBytes = it.size * src.elemSize(); + const size_t totalBytes = it.nplanes * planeBytes; + const uchar* srcStart = src.isContinuous() ? src.data : src.datastart; + const uchar* srcEnd = src.isContinuous() ? src.data + totalBytes : src.dataend; + const uchar* dstStart = dst.isContinuous() ? dst.data : dst.datastart; + const uchar* dstEnd = dst.isContinuous() ? dst.data + totalBytes : dst.dataend; + std::less less; + if (less(srcStart, dstEnd) && less(dstStart, srcEnd)) + return false; + + int order[CV_CN_MAX]; + std::fill_n(order, channels, -1); + std::bitset used; + bool identity = true; + for (size_t pair = 0; pair < npairs; ++pair) + { + const int from = fromTo[2 * pair]; + const int to = fromTo[2 * pair + 1]; + if (from < 0 || order[to] >= 0 || used[from]) + return false; + order[to] = from; + used[from] = true; + identity &= from == to; + } + + if (identity) + { + for (size_t plane = 0; plane < it.nplanes; ++plane, ++it) + std::memcpy(it.ptrs[1], it.ptrs[0], planeBytes); + return true; + } + if (bytes) + { + CV_CPU_DISPATCH(permuteByteChannels, (it, order, channels), CV_CPU_DISPATCH_MODES_ALL); + } + if (wide32) + { + CV_CPU_DISPATCH(permuteWideChannels, (it, order, channels), CV_CPU_DISPATCH_MODES_ALL); + } + CV_CPU_DISPATCH(permuteSmallChannels, (it, order, channels, elemSize), CV_CPU_DISPATCH_MODES_ALL); +} + } // cv:: @@ -156,6 +219,9 @@ void cv::mixChannels( const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, cons MixChannelsFunc func = getMixchFunc(depth); CV_Assert(func); + if (nsrcs == 1 && ndsts == 1 && tryPermuteChannels(src[0], dst[0], fromTo, npairs, it)) + return; + for( i = 0; i < it.nplanes; i++, ++it ) { for( k = 0; k < npairs; k++ ) diff --git a/modules/core/test/test_operations.cpp b/modules/core/test/test_operations.cpp index 30fe8c6078..9daa4ee0dd 100644 --- a/modules/core/test/test_operations.cpp +++ b/modules/core/test/test_operations.cpp @@ -47,6 +47,128 @@ namespace opencv_test { namespace { +typedef testing::TestWithParam > Core_MixChannelsInterleaved; + +TEST_P(Core_MixChannelsInterleaved, interleaved_permutations) +{ + const int channels = get<0>(GetParam()); + const int depth = get<1>(GetParam()); + const bool roi = get<2>(GetParam()); + const int type = CV_MAKETYPE(depth, channels); + const Rect region(roi ? 1 : 0, roi ? 2 : 0, 39, 19); + Mat input(region.y + region.height, region.x + region.width + (roi ? 3 : 0), type); + Mat output(input.size(), type); + Mat expected = Mat::zeros(input.size(), type); + Mat bytes(input.rows, static_cast(input.cols * input.elemSize()), CV_8U, input.data, input.step); + theRNG().fill(bytes, RNG::UNIFORM, 0, 256); + + const Mat src = input(region); + Mat dst = output(region); + std::vector planes; + split(src, planes); + std::vector order = {0, 1, 2, 3}; + order.resize(channels); + do + { + output.setTo(Scalar::all(0)); + std::vector fromTo; + std::vector expectedPlanes(channels); + for (int to = channels - 1; to >= 0; --to) + { + fromTo.push_back(order[to]); + fromTo.push_back(to); + expectedPlanes[to] = planes[order[to]]; + } + Mat expectedRoi = expected(region); + merge(expectedPlanes, expectedRoi); + cv::mixChannels(&src, 1, &dst, 1, fromTo.data(), order.size()); + ASSERT_EQ(0, std::memcmp(expected.data, output.data, output.total() * output.elemSize())) + << testing::PrintToString(order); + } + while (std::next_permutation(order.begin(), order.end())); +} + +INSTANTIATE_TEST_CASE_P(Core, Core_MixChannelsInterleaved, testing::Combine( + testing::Values(2, 3, 4), + testing::Values(CV_8U, CV_16F, CV_32F), + testing::Bool())); + +TEST(Core_MixChannels, overlapping_interleaved_arrays) +{ + std::vector pixels(39, Vec3b(11, 22, 33)); + Mat src(1, static_cast(pixels.size()) - 1, CV_8UC3, pixels.data()); + Mat dst(src.rows, src.cols, src.type(), pixels.data() + 1); + const int fromTo[] = {0, 1, 1, 2, 2, 0}; + cv::mixChannels(&src, 1, &dst, 1, fromTo, 3); + + EXPECT_EQ(Vec3b(11, 22, 33), pixels.front()); + EXPECT_EQ(Vec3b(33, 11, 22), pixels[1]); + EXPECT_EQ(Vec3b(11, 11, 11), pixels.back()); +} + +TEST(Core_MixChannels, identity_mapping_wide_row) +{ + applyTestTag(CV_TEST_TAG_MEMORY_6GB); + + const int cols = INT_MAX / 8 + 1; + Mat src(1, cols, CV_8UC(8)), dst(src.size(), src.type()); + const size_t bytes = src.total() * src.elemSize(); + std::memset(src.data, 0, bytes); + src.data[0] = 11; + src.data[bytes - 1] = 22; + const int fromTo[] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}; + + cv::mixChannels(&src, 1, &dst, 1, fromTo, 8); + EXPECT_EQ(0, std::memcmp(src.data, dst.data, bytes)); +} + +TEST(Core_MixChannels, partial_mapping_with_full_pair_count) +{ + const Mat src(7, 39, CV_8UC4, Scalar(11, 22, 33, 44)); + Mat dst(src.size(), src.type(), Scalar::all(77)); + const Mat expected(src.size(), src.type(), Scalar(44, 0, 77, 77)); + const int fromTo[] = {0, 0, 2, 0, -1, 1, 3, 0}; + cv::mixChannels(&src, 1, &dst, 1, fromTo, 4); + EXPECT_EQ(0, cvtest::norm(dst, expected, NORM_INF)); +} + +typedef testing::TestWithParam > Core_MixChannelsWideInterleaved; + +TEST_P(Core_MixChannelsWideInterleaved, wide_interleaved_permutations) +{ + const int type = get<0>(GetParam()); + const int channels = CV_MAT_CN(type); + const bool roi = get<1>(GetParam()); + const Rect region(roi ? 1 : 0, 0, channels <= 16 ? 39 : 257, channels <= 16 ? 37 : 256); + Mat source(region.height, region.x + region.width + (roi ? 1 : 0), type); + Mat destination = Mat::zeros(source.size(), type); + Mat expected = Mat::zeros(source.size(), type); + Mat bytes(source.rows, static_cast(source.cols * source.elemSize()), CV_8U, source.data, source.step); + theRNG().fill(bytes, RNG::UNIFORM, 0, 256); + + const Mat src = source(region); + Mat dst = destination(region); + Mat expectedROI = expected(region); + std::vector planes; + split(src, planes); + std::vector fromTo; + for (int channel = 0; channel < channels; ++channel) + { + fromTo.push_back(channels - 1 - channel); + fromTo.push_back(channel); + } + std::reverse(planes.begin(), planes.end()); + merge(planes, expectedROI); + cv::mixChannels(&src, 1, &dst, 1, fromTo.data(), channels); + ASSERT_EQ(0, std::memcmp(expected.data, destination.data, destination.total() * destination.elemSize())); +} + +INSTANTIATE_TEST_CASE_P(Core, Core_MixChannelsWideInterleaved, testing::Combine( + testing::Values(CV_8UC(5), CV_8UC(6), CV_8UC(7), CV_8UC(8), CV_8UC(9), CV_8UC(10), + CV_8UC(11), CV_8UC(12), CV_8UC(13), CV_8UC(14), CV_8UC(15), CV_8UC(16), + CV_32FC(32), CV_32FC(64), CV_32FC(CV_CN_MAX), CV_32SC(32), CV_32UC(32)), + testing::Bool())); + class CV_OperationsTest : public cvtest::BaseTest { public: