代码之家  ›  专栏  ›  技术社区  ›  Coder1990

无法在R中使用readJPEG读取图像

  •  0
  • Coder1990  · 技术社区  · 1 年前

    我的R数据帧中有一列包含到图像的链接。 如。 https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg

    当我尝试使用readJPEG读取它时,它给出了以下错误-

    “无法打开 https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg"

    所以我试着单独运行它来检查发生了什么,但它给出了相同的错误。

    readJPEG("https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg")
    

    我不知道如何调试,因为错误消息中没有提供太多细节。

    0 回复  |  直到 1 年前
        1
  •  2
  •   r2evans    1 年前

    该函数不接受URL。

    从…起 ?jpeg::readJPEG :

    Usage:
    
         readJPEG(source, native = FALSE)
         
    Arguments:
    
      source: Either name of the file to read from or a raw vector
              representing the JPEG file content.
    
      native: determines the image representation - if ‘FALSE’ (the
              default) then the result is an array, if ‘TRUE’ then the
              result is a native raster representation.
    

    固定代码:

    tf <- tempfile(fileext = ".jpeg")
    download.file("https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg", tf)
    # trying URL 'https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg'
    # Content type 'image/jpeg' length 40093 bytes (39 KB)
    # ==================================================
    # downloaded 39 KB
    stuff <- jpeg::readJPEG(tf)
    class(stuff)
    # [1] "array"
    unlink(tf) # if you want/need to clean up the temp file
    
        2
  •  2
  •   Allan Cameron    1 年前

    由于函数采用原始矢量,我们可以使用 readBin 直接从url中读取jpeg作为原始矢量,并将其传递给 readJPEG :

    img <- "https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg" |>
      readBin("raw", 1e6) |>
      jpeg::readJPEG() 
    

    现在 img 是一个rgb数组,因此我们可以执行以下操作,例如:

    plot(as.raster(img))
    

    enter image description here

    推荐文章