【问题标题】:Is there a way to read an image from a url on openCV?有没有办法从 openCV 上的 url 读取图像?
【发布时间】:2022-01-19 19:24:54
【问题描述】:

我正在尝试读取网站上的图像,例如,我将图像链接传递给 cv2.imgread(https://website.com/photo.jpg)。但它返回一个NoneType。错误说TypeError: cannot unpack non-iterable NoneType object

这是我的代码:

def get_isbn(x):
    print(x)
    
    image = cv2.imread(x)
    
    
    print(type(image))
    detectedBarcodes = decode(image)
    for barcode in detectedBarcodes:
        (x, y, w, h) = barcode.rect
        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 5)

        # print(barcode.data)
        # print(type(barcode.data))
        byte_isbn = barcode.data
        string_isbn = str(byte_isbn, encoding='utf-8')
        
        return string_isbn

x 是我的 url 作为参数。

【问题讨论】:

  • 用字符串 url 尝试 VideoCapture
  • 我只想处理一张图片,
  • VideoCapture 可以读取图像文件。也许它也可以读取图像文件的网址?

标签: opencv cv2 opencv-python


【解决方案1】:

你需要将链接转换为数组,然后用opencv解码。

功能

import numpy as np
import urllib
import cv2
def url_to_image(url):
    resp = urllib.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image

合并到您的代码中

import numpy as np
import urllib
import cv2
def url_to_image(url):
    resp = urllib.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image
def get_isbn(x):
    print(x)

image = url_to_image(x)


print(type(image))
detectedBarcodes = decode(image)
for barcode in detectedBarcodes:
    (x, y, w, h) = barcode.rect
    cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 5)

    # print(barcode.data)
    # print(type(barcode.data))
    byte_isbn = barcode.data
    string_isbn = str(byte_isbn, encoding='utf-8')
    
    return string_isbn

【讨论】:

    【解决方案2】:

    在某些情况下,我们可以将图像视为由单帧组成的视频。

    它并非在所有情况下都有效,并且在执行时间方面效率不高。
    优点是该解决方案仅使用 OpenCV 包(例如,它也可以在 C++ 中工作)。

    代码示例:

    import cv2
    
    image_url = 'https://i.stack.imgur.com/fIDkn.jpg'
    
    cap = cv2.VideoCapture(image_url)  # Open the URL as video
    
    success, image = cap.read()  # Read the image as a video frame
    
    if success:
        cv2.imshow('image ', image)  # Display the image for testing
        cv2.waitKey()
    
    cap.release()
    cv2.destroyAllWindows()
    

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 1970-01-01
      • 2021-05-15
      • 2018-04-30
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      相关资源
      最近更新 更多