【问题标题】:Bit Rotation operation位旋转操作
【发布时间】:2011-03-10 02:45:37
【问题描述】:

有没有办法使位旋转操作可逆?我的意思是,如果有图像 X(大小 256 * 256 *3),那么在进行位旋转时,将获得图像 Y。然后对Y进行位旋转,我们得到图像X。另外,如何解决位溢出,以免信息丢失。

【问题讨论】:

  • 旋转不会丢失信息,它只是移动它。

标签: matlab


【解决方案1】:

更新:我已将我在下面发布的代码改进为 a complete function,其中包含错误检查、帮助文档以及对无符号整数数组进行操作的能力 双精度变量就像相关的内置函数BITSHIFT。我建议使用我在上面链接到的较新版本,而不是下面发布的旧版本。


MATLAB 没有内置的位循环函数,BITSHIFT 函数会丢弃溢出的位。但是,您可以基于existing bit operations 实现自己的位旋转功能。这是我拼凑的一个简单的第一次通过版本(没有错误检查):

function data = bit_rotate(data,nBits)
  dataBits = log2(double(intmax(class(data)))+1);  %# Number of bits in data
  nBits = rem(nBits,dataBits);  %# No need to rotate by dataBits bits or more
  if nBits == 0  %# No bit rotation needed, just return
    return
  end
  shiftedData = bitshift(data,nBits);              %# Bit shift the data
  lostData = bitxor(data,bitshift(shiftedData,-nBits));  %# Find the lost bits
  rotatedData = bitshift(lostData,nBits-sign(nBits)*dataBits);  %# Rotate them
  data = shiftedData+rotatedData;  %# Add the rotated bits to the shifted bits
end

还有一些测试数据:

>> B = uint8(208);     %# An unsigned 8-bit integer value
>> disp(dec2bin(B,8))  %# Display the bit pattern of B
11010000
>> disp(dec2bin(bit_rotate(B,2),8))   %# Rotate left by 2 bits
01000011
>> disp(dec2bin(bit_rotate(B,-2),8))  %# Rotate right by 2 bits
00110100

请注意,bit_rotate 也可以对 data 的任何大小的矩阵输入进行操作,只要它是无符号整数类型即可。

【讨论】:

  • @gnovice,正向位旋转工作正常。但是,我使用灰度图像进行处理,无法通过相同的逻辑恢复原始图像!!该怎么做?
  • @gavisha:如果不看你在做什么,我无法知道出了什么问题。我测试的图像工作正常。例如:img = imread('cameraman.tif'); rotimg = bit_rotate(img,2); figure; imshow(rotimg); recimg = bit_rotate(rotimg,-2); figure; imshow(recimg);
  • 我做的完全一样,虽然我选择了 10 位而不是 2 位。如果大小为 m*n,是否可以旋转 m 位?
  • @gavisha:你的图片是 8 位的吗?如果是这样,你不应该旋转超过 8 位,因为那是没有意义的。您只需将这些位旋转回其原始位置,然后再旋转得更远。换句话说,将 8 位旋转 10 相当于旋转 2。我将在上面的代码中添加针对这种情况的更正。
  • @gnovice。好的,这有点道理。因此,如果图像的大小是 512*512*3(RGB),那么在这种情况下可以旋转的最大位数是多少?最后,如果我得出的结论是 Bitshift 不可逆但有错误,请纠正我称为循环位移的东西,您提供的代码是使用现有位移的位旋转操作。
【解决方案2】:

当然,位旋转是可逆的,只需反向旋转相同的量即可。

Wikipedia 提供了有关如何在 C 中使用基本位移位来实现它的很好的信息,这样您就不会溢出: http://en.wikipedia.org/wiki/Circular_shift

而且我想如果这个操作在 Matlab 中被称为“位旋转”,它肯定不会溢出。

【讨论】:

  • 感谢 Oli 的宝贵意见。
猜你喜欢
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多