首页 > 解决方案 > python中的按位和图像分辨率计算。有人可以解释代码吗?

问题描述

with open("image.jpg",'rb') as file:
    file.seek(163)
    a = file.read(2)
    height = (a[0] << 8) - a[1]
    a = file.read(2)
    width = (a[0] << 8) - a[1]
print(str(height) + " x " + str(width))

我还在学习python。我知道按位运算符左移和右移。但我不明白这段代码。

我的理解是:

  1. 我们将二进制读取的图像作为文件打开。
  2. 用 将光标移动到 163 file.seek()。为什么是163?
  3. 读取大小为 2 个字节的文件。为什么?

我根本不明白第 4 行和第 6 行。打印功能还可以。

我尝试使用 Pillow 和 cv2。但万一我不能使用这些模块,我想我应该知道这个。

标签: pythonbit-shift

解决方案


这是粗略和丑陋但SOF0包含图像高度和宽度的阅读,请参阅本文末尾附近。其实也是不对的。它应该是:

with open("image.jpg",'rb') as file:
   file.seek(163)
   a = file.read(2)
   height = (a[0] << 8) | a[1]     # It should be ORed in not subtracted
   print(height)
   a = file.read(2)
   width = (a[0] << 8)  | a[1]     # It should be ORed in not subtracted
   print(width)

另请参阅有关 JPEG 的Wikipedia条目。


作为一个小例子,让我们用ImageMagick制作一个 640x480 的红色 JPEG :

magick -size 640x480 xc:red image.jpg

现在让我们寻找SOF0标记FF C0

xxd -c16 -g1 -u image.jpg | grep -A2 "FF C0"
00000090: 10 10 10 10 10 10 10 10 10 10 10 10 10 10 FF C0  ................
000000a0: 00 11 08 01 E0 02 80 03 01 11 00 02 11 01 03 11  ................
000000b0: 01 FF C4 00 15 00 01 01 00 00 00 00 00 00 00 00  ................

如果我们检查 640 和 480 在十六进制中的样子:

printf "%x %x" 480 640
1e0 280

你可以在文件的偏移量 163 处看到它们,因为偏移量a0是 160,而我们是从那开始的 3 个字节。


推荐阅读